使用linux的fork函数,可以进行进程的创建。如果fork函数返回为0,则为子进程;如果大于0,则为父进程;如果小于0则创建进程失败,编写代码如下:
- #include <sys/types.h>
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <unistd.h>
-
-
int main(int argc, char *argv[])
-
{
-
pid_t pid;
-
if((pid=fork()) < 0){
-
printf("fork error!\n");
-
exit(1);
-
}
-
else if(pid == 0){
-
printf("child process is printing.\n");
-
}
-
else {
-
printf("parent process is printing.\n");
-
}
-
exit(0);
-
}
执行情况如下:
peng@ubuntu:~/src/test/c/linuxc$ gcc 6.1.c
peng@ubuntu:~/src/test/c/linuxc$ ./a.out
parent process is printing.
child process is printing.
阅读(2880) | 评论(0) | 转发(0) |