父进程和子进程的关系(Linux C 编程)

父进程和子进程是并行运行的,先运行哪个是不确定的,在小红帽系统中,先运行的是子进程,在ubuntu系统中,父进程是先运行的。

其实谁先运行不重要了,一般在编程中,把父进程当做守护进程使用,用一个waitpid(pid,&statloc,0) != pid 等待子进程的结束,父进程一直阻塞在这个函数中,阻塞或不阻塞跟第三个参数有关系。

举例:

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
  pid_t pid;

  pid = fork();					// 创建进程
  if (-1==pid) {					// 创建进程失败
    printf("Error to create new process!\n");
    return 0;
  }
  else if (pid==0) {				// 子进程
    printf("Child process!\n");
  } else {						// 父进程
    printf("Parent process! Child process ID: %d\n", pid);
  }

  return 0;
}

结果(Ubuntu中):明显先打印了父进程
在这里插入图片描述

把父进程当做守护进程使用

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
  pid_t pid, pid_wait;
  int status;

  pid = fork();							// 创建子进程
  if (-1==pid) {							// 检查是否创建成功
    printf("Error to create new process!\n");
    return 0;
  }
  else if (pid==0) {						// 子进程
    printf("Child process!\n");
  } else {								// 父进程
    printf("Parent process! Child process ID: %d\n", pid);
    pid_wait = waitpid(pid, &status, 0);		// 等待指定进程号的子进程
    printf("Child process %d returned!\n", pid_wait);
  }

  return 0;
}

结果(Ubuntu中):父进程等待了子进程结束
在这里插入图片描述

发布了131 篇原创文章 · 获赞 44 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_38769551/article/details/103646718