操作系统——在父进程中创建子进程

操作系统——创建进程

  1. 创建一个c语言文件,我写的是test.c且把它放在了mm文件夹里面了(直接贴代码)
#include
#include
#include
#include
#include
#include
 
 
int main()
{

    pid_t child;
    int status;
 
    child=fork();//创建子进程
    if(child<0)
    {
        printf("fail to creat the prosses!\n");
        exit(1);
    }
 
    else if(child==0)
    {
        printf("the child prosses!\n");
 	  	printf("the child prosses pid: %d!\n",getpid());
        exit(1);
    }
    else
    {
        waitpid(child, &status, 0);
        printf("the father prosses!\n");
 	 	printf("the father prosses pid: %d!\n",getpid());
        exit(4);
    }
 
    return 1;
}

2.在linux终端运行该文件

  1. 使用指令gcc dsc.c编译文件
  2. 使用指令./a.out输出
  3. 结果如下(这里直接把结果复制下来)
    [xiaoxiao@localhost mm]$ gcc test.c
    [xiaoxiao@localhost mm]$ ./a.out
    the child prosses!
    the child prosses pid: 9529!
    the father prosses!
    the father prosses pid: 9528!
    [xiaoxiao@localhost mm]$

3.收获
fork()用于从已存在进程中创建一个新进程。新进程被称为子进程,而原来的进程被称为父进程。这两个分别带回它们各自的返回值,其中父进程的返回值是子进程的进程号,而子进程则返回0,大于0的则是父进程。所以,可以通过返回值来判定该进程是父进程还是子进程。

你可能感兴趣的:(操作系统)