Linux C 学习日记(4) 多进程操作

题目一:

有3个进程,其中一个为父进程,其余为父进程的子进程,分别打印这三个进程的进程号,父进程号,进程组号。

                                      程序一:
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
  pid_t pid1;
  pid_t pid2;

  pid1=fork();  //创建进程
  if(pid1==0)             //第一个子进程
  {
     printf("this is first  child process!\n");
     printf("%d\n",getpid());  //输出进程号
     printf("%d\n",getppid()); //输出父进程号
     printf("%d\n",getpgid(pid1));  //输出进程组号
  }
  else if(pid1>0)   //父进程
  {
     printf("this is parent process!\n");
     printf("%d\n",getpid());    //输出进程号  (通过和下面那个父进程号对比,证明两个进程是同一个。它们的进程号是相同的。)
     printf("%d\n",getpgid(pid1));
     sleep(3);

    pid2=fork();         //在父进程里 再次使用fork() 创建进程
     if(pid2==0)         //第二个子进程
         {
            printf("this is second  child process!\n");
            printf("%d\n",getpid());  //输出进程号
            printf("%d\n",getppid()); //输出父进程号
            printf("%d\n",getpgid(pid2));  //输出进程组号
         }
      else if(pid2>0)    //父进程
         {
            printf("this is parent process!\n");
            printf("%d\n",getpid());  //输出进程号
            printf("%d\n",getpgid(pid2));  //输出进程组号
            sleep(5);
         }
  }
 return 0;
 }

题目二

有3个进程,其中一个为父进程,其余为父进程的子进程,其中一个子进程运行"ls -l"指令,另一个子进程在暂停5s后退出,父进程不阻塞自己,并等待子进程的退出信息,待收到该信息,父进程返回。

#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
  pid_t pid1;
  pid_t pid2;
  pid_t pid3;

  pid1=fork();
  if(pid1==0)
  {
     printf("this is first  child process!\n");
     printf("first child execute ls-l\n");
     execlp("ls","-l","/work",(char*)0);   //执行 execlp函数  
     exit(0);    //退出
  }
  else if(pid1>0)
  {
     printf("this is parent process!\n");
     pid2=fork();     //在父进程中再次使用fork()函数创建进程
       if(pid2==0)
         {
            printf("this is second  child process!\n");
            printf("it will sleep for 5s\n");
            sleep(5);    //暂停5秒
            exit(0);     //退出
         }
else
         {
             do
              {
                 pid3=waitpid(pid2,NULL,WNOHANG);   //父进程 使用wait()函数等待子进程 pid2
                 if(pid3==0)
                    {
                         printf("the second  chile is working!\n");
                         sleep(1);
                    }
               }while(pid3==0);
            if(pid3==pid2)
               {
                  printf("child  is over!\n");
                  printf("parent is over!\n");
               }                       
         }
  }
return 0;
}

猜你喜欢

转载自blog.csdn.net/Black_goat/article/details/83991219