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 |
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 |
I've used advisory file locking with success. See man fcntl and look for F_GETLK.
Kevin Barry |
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. |