[英]How to work with parent and child processes with the fork() function?
我正在嘗試編寫一個程序來打印從 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);
}
output 是:
6
7
8
9
10
1
2
3
4
5
我是 UNIX 進程的新手,所以我不明白為什么首先打印父進程 output(從 6 到 10)。 父進程的執行是否優先於子進程? 如果我希望子進程首先運行(即首先打印 1 - 5),我該怎么做?
這可以滿足您的要求:
#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);
}
進行了一些更改,首先讓孩子 go。
id < 0
的檢查,以打印錯誤。在測試中,這是 output:
1
2
3
4
5
6
7
8
9
10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.