Linuc C 编程实例1
1 get.c
#include <stdio.h> #include <string.h> #include <strings.h>int main(void) {char buf[100];bzero(buf, 100);fgets(buf, 100, stdin);printf("you have input %d letters\n", strlen(buf));return 0; }bzero函數(shù)
原型:extern void bzero(void *s, int n);?
用法:#include <string.h>?
功能:置字節(jié)字符串s的前n個字節(jié)為零。?
bzero無返回值。
? ? 這和Windows不一樣;?
2 fork1.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h>int global = 22;int main(void) {int test = 0,stat;pid_t pid;pid = fork();if(pid < 0){perror("fork");return -1;}else if(pid == 0){global++;test++;printf("global = %d test = %d Child,my PID is %d\n",global,test,getpid());exit(0);}else{global += 2;test += 2;printf("global = %d test = %d Parent,my PID is %d\n",global,test,getpid());exit(0);} }?fork函數(shù)的返回情況是,
pid_t pid=fork();
?? ?if(pid==0){ ?//子進程
?? ?}
?? ?if(pid>0){//父進程
?? ?}
?? ?if(pid<0){//出錯
?? ?}
3 exev.c
#include <stdio.h> #include <unistd.h>int main() {if(execlp("ps","ps","-ef",NULL) < 0){perror("execlp error");return -1;}return 0; }? ?Linux 中有6個以 exec 開頭的函數(shù),
#include <stdio.h>
函數(shù)原型?? ?
int execl (const char *path,const char *arg,...);
int execv (const char *path, char *const argv[]);
int execle (const char *path,const char *arg,....,char *const envp[]);
int execve(const char *path, char ?const *argv[],char *const envp[]);
int execlp (const char *file,const char *arg,...);
int execvp (const char *file, char *const argv[]);
函數(shù)返回值?? ?-1;出錯
exec 函數(shù)族可以默認使用系統(tǒng)的環(huán)境變量,也可以傳入指定的環(huán)境變量,這里,以"e" (Enviromen) 結(jié)尾的兩個函數(shù)execle 、execve 就可以在 envp[] 中傳遞當前進程所使用的環(huán)境變量;
4 ftest1.c
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h>int main(int argc, char const *argv[]) {int fd = -1; //文件描述符//打開文件fd = open( "mytest.txt", O_RDWR );if ( -1 == fd ) {printf("文件打開失敗\n");}else {printf("文件打開成功,fd=%d\n", fd );}//讀取文件int count = 0;char buf[20];count = read( fd, buf, 50 );if ( -1 == count ) {printf("文件讀取失敗\n");}else {printf("文件讀取成功,實際讀取的字節(jié)數(shù)目為:%d\n內(nèi)容為%s\n", count, buf );}//關(guān)閉文件close( fd );return 0; }? ? 文件操作;文件要先存在;?
運行情況如下;
?
總結(jié)
以上是生活随笔為你收集整理的Linuc C 编程实例1的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VC++ 查看C++代码的汇编代码列表
- 下一篇: 初步了解BIM模型和超图相关操作