简体   繁体   中英

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:

#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:

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. 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?

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.

  • Added a check for id < 0 with fork(), to print the error.
  • Added a call to wait() to allow the child to exit before the parent loop.
  • Check the return from wait to make sure it succeeded.
  • Several headers were added for functions used.
  • Formatting changes, largely irrelevant.

In testing, this is the output:

1
2
3
4
5
6
7
8
9
10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM