Hi
I have a large C program which executes continuously, that is listening to the user inputs, it is in an event loop. Now I want to have two different functions in that code to be executed simultaneously, in parallel. I tried to use fork() but the problem is in fork each process will be executed after the other one has exited, but my program never exit. Using pthreads didnt help...
Any ideas, maybe I'm missing something!

Edited 5 Years Ago by manaila: n/a

Can you show us the code? And which functions you want to use. You don't always have to thread.

fork() creates a copy of a parent process and all the descriptor is opened by the parent process is also shared by forked children.

If you use fork() to create children, then parent process or a child process doesn't need to wait for other children or parent to get finished.

In plain words all fork() children should be able to run simultaneously.

As sergent said, can we see the code you are using to fork()?

You don't need to post up the whole program, just post up the smallest example of the problem you're having, in a snippet of code that runs and shows the problem.

Sometimes, the doctor must actually examine the patient. ;)

I used fork() and the processes are now running simultaneously, but the problem is since I included everything inside the while(1) loop, I am unable to use exit() in both the parent process and the child process without exiting the whole program. So when I left one exit() function, after some time "forking" stops: Unable to fork: Resource temporarily unavailable
How can I make the created processes to exit whilst still making sure that the program keeps running?
Below is the main function where I used the fork:

int main(int argc, char **argv)
{
      while(1)
      {
	   pid_t pID = fork();
	   if (pID == 0) //child process
	   {
                read(fd, Buffer, 2);
                display();
		exit(0);
           }
	   else if (pID < 0) //fork failed
	   {
		perror ("Unable to fork");
		exit(1);				
	   }
	   else //parent process
	   {
		read(fd, Buffer, 2);
		display();
                //when I put exit(0); here the whole program terminates!!!
	   }
      }
      return 1;
}

Edited 5 Years Ago by manaila: n/a

Ooops!!
So when I put the pid_t pID = fork(); outside the while(1) loop the fork bomb wont exist...I guess!
What about the exit(0); at the end of the if...else statements. When they are included, the program does not run forever; but when they are excluded everything just goes fine, but I am afraid this may lead to fork bomb thing or any other undesirable system status!
The other thing is when I am working on one process, the other process keeps popping in and thus making the whole system slow with those anoying interrupts. How can I switch between the processes so that I can work on only one process at a time without the other process interrupting?

This article has been dead for over six months. Start a new discussion instead.