fork.txt

来自「在linux或unix中」· 文本 代码 · 共 85 行

TXT
85
字号
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
main( )
{
int p1,p2;
while ((p1=fork())== -1); //创建子进程P1
if (p1==0) putchar(‘b’); //在子进程p1中输出b
else
{
while ((p2=fork())== -1); //创建子进程P2
if(p2==0)  putchar(‘c’); //在子进程p2中输出c
else putchar(‘a’); //在父进程输出a
}
}
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
main()
{   int childpid;
     childpid = fork();
    if(-1 == childpid )   perror("fork");
   else if(0 == childpid)  //now in child process
     {
       printf("now in child process.\n");
    }
   else // in parent process
    {
      printf("now in parent process.\n");
    }
}
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
main(int argc, char *argv[])
{       pid_t pid = getpid();
        printf("my process id is %d! ", pid);
        pid = fork(); // create a child process
        if(pid == 0)
        {// in the child process
                printf("I am child process, my process id is %d! ", getpid());
        }
        else if(pid > 0)
        {// in the parent process
                printf("I am parent process, my process id is %d! ", getpid());
        }
        else
        {// unabled create child process
                perror("unabled create child process");
        }
}


#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
main(int argc, char *argv[])
{       pid_t pid = getpid();
        int i = 12;
        int status = 0;
        if(pid = fork())
        {
                // do nothing
        }
        else if(pid == 0)
        {
                i = 111;
        }
        else if(pid < 0)
        {
                perror("unabled create a child process ");
        }
        if(pid > 0)
        {
                if((pid = waitpid(pid, &status, 0)) < 0)
               {
                        perror("waitpid error");
                }
        }
        printf("i is %d ", i);
        return 0;
}


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?