簡體   English   中英

如何使用 fork() function 處理父進程和子進程?

[英]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。

  • 使用 fork() 添加了對id < 0的檢查,以打印錯誤。
  • 添加了對 wait() 的調用,以允許子循環在父循環之前退出。
  • 檢查等待返回以確保它成功。
  • 為使用的功能添加了幾個標題。
  • 格式更改,在很大程度上無關緊要。

在測試中,這是 output:

1
2
3
4
5
6
7
8
9
10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM