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;
		exit(-1);
	}
	else if(pid == 0)//Child process
	{
		cout << "In child process!" << endl;
	}

	else if(pid > 0)//Parent process
	{
		cout << "Parent process is waiting child..." << endl;
		wait();
		cout << "Child completed its task." << endl;
		return 0;
	}

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.