Reputation: 339
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 (i.e. 1 - 5 printed first), how can I do it?
Upvotes: 2
Views: 186
Reputation: 6074
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.
id < 0
with fork(), to print the error.In testing, this is the output:
1
2
3
4
5
6
7
8
9
10
Upvotes: 1