LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How can I allow interleave output when I run commands concurrently (https://www.linuxquestions.org/questions/programming-9/how-can-i-allow-interleave-output-when-i-run-commands-concurrently-864544/)

longli 02-23-2011 09:53 AM

How can I allow interleave output when I run commands concurrently
 
Hi, guys:


I am working on the shell using c language. I just would like to ask when I run some command in the backgrounds, how can I allow interleave out?

I want to the output like this:

shell> command1
shell> command2 &
shell> command3


This is the code to run the command:

pid=fork();

if (pid==0&&bg==0) // foreground
{


exec(command); // execute a command

exit(1);

}

else if (pid==0&&bg==1) // background
{

setpgid(pid,0);


exec(command); // execute a command

exit(1);
}

else if (bg!=1)
{
waitpid();

}




Thanks

paulsm4 02-24-2011 03:18 PM

There's no easy way to control what gets written when you share output to your /dev/tty between multiple (essentially independent) processes.

One alternative is to make the processes work in lockstep (instead of in parallel). Not a good solution ;)

Another is to create some kind of semaphore (either a bona fide "ipc semaphore", or some global alternative) to regulate who does a "printf()" and who waits. Again - not a good solution.

Another choice is to redirect stdout to a disk file (e.g. "my_child_prog > $$.txt"), and then have the "master" process read the individual files at its leisure.

'Hope that helps .. PSM

ta0kira 02-25-2011 03:35 AM

I've used advisory file locking with success. See man fcntl and look for F_GETLK.
Kevin Barry

prowla 02-25-2011 04:34 AM

You could write something that opens a pipe reading from each command and does (pseudo code)

read(pipe1,s); print s;
read(pipe2,s); print s;
read(pipe3,s); print s;

Alternatively, if it's not for real-time, you could tag each line with a number and join them after.


All times are GMT -5. The time now is 09:34 AM.