[英]How to work with parent and child processes with the fork() function?
I am trying to write a program that will print numbers from 1 to 10, but I want the first five numbers to be printed by the child processes, and the last 5 should be printed by the parent processes:我正在尝试编写一个程序来打印从 1 到 10 的数字,但我希望前五个数字由子进程打印,后五个数字应该由父进程打印:
#include <unistd.h>
#include <stdio.h>
#include "process.h"
/**
* main - Entry point for my program
*
* Return: On success, it returns 0.
* On error, it returns 1
*/
int main(void)
{
int id = fork();
int n, i;
if (id == 0)
n = 1;
else
n = 6;
for (i = n; i < n + 5; i++)
printf("%d\n", i);
return (0);
}
The output is: output 是:
6
7
8
9
10
1
2
3
4
5
I am new to UNIX processes, so I dont understand why the parent process output (from 6 - 10) is being printed first.我是 UNIX 进程的新手,所以我不明白为什么首先打印父进程 output(从 6 到 10)。 Does the execution of the parent process take precedence over the child process?父进程的执行是否优先于子进程? If I want the child processes to run first (ie 1 - 5 printed first), how can I do it?如果我希望子进程首先运行(即首先打印 1 - 5),我该怎么做?
This does what you wish:这可以满足您的要求:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
/**
* main - Entry point for my program
*
* Return: On success, it returns 0.
* On error, it returns 1
*/
int main(void)
{
int id = fork();
int n, i;
if (id < 0) {
perror("fork failed: ");
exit(1);
} else if (id == 0) {
n = 1;
} else {
int status, cid;
n = 6;
cid = wait(&status);
if (cid != id) {
perror("fork failed: ");
exit(1);
}
}
for (i = n; i < n + 5; i++) {
printf("%d\n", i);
}
return (0);
}
A couple changes were made to have the children go first.进行了一些更改,首先让孩子 go。
id < 0
with fork(), to print the error.使用 fork() 添加了对id < 0
的检查,以打印错误。In testing, this is the output:在测试中,这是 output:
1
2
3
4
5
6
7
8
9
10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.