Hey there;

I'm having trouble with fork() and wait() functions.

In the code below I'm trying to create a child process and first let the child process do its work then parent process finish execution. I use wait() function in the parent process but the output shows that child process finishes last.

Expected Output: Lines with "*" may vary in ordering of course

Parent process is waiting child...*
In child process! *
Child completed its task.

Actual Output:
Parent process is waiting child...
Child completed its task. //How can child complete its task withour printing to the screen first ?
In child process!

#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <stdlib.h>
#include <sys/wait.h>

using namespace std;

int main()
	pid_t pid;

	pid = fork();

	if(pid < 0)//Error occurs
		cout << "Error creating child process." << endl;
	else if(pid == 0)//Child process
		cout << "In child process!" << endl;

	else if(pid > 0)//Parent process
		cout << "Parent process is waiting child..." << endl;
		cout << "Child completed its task." << endl;
		return 0;
5 Years
Discussion Span
Last Post by Tellalca

Wow! The problem was with the text editor. It did not compile the latest version of the code. I like Linux but when it comes to IDE Visual Studio absolutely rules. Is it too hard to create a good and responsive IDE???

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.