[LCP]Fork freezes when forking more then one
juman
juman at chello.se
Mon Aug 25 19:57:02 UTC 2003
Hi,
I'm trying to write a software that will fork processes and control
their stdin/stdout. Forking just one process with a main looking like
everything works:
int main(void)
{
prog *a;
a = runthis ("/root/mp3/musidab/src/test.awk");
write_to_child (a, "testa.mp3");
stoprunning (a);
sleep (5);
return 0;
}
The sleep is only so I can check which processes is running.
But if I run 2 processes as can be seen in the real program the software
freezes when trying to read the output of the first process. Can somebody help
me with what I do wrong when trying to exit the forked process and read their
output?
--- The software start ---
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#define OK 0
#define FAIL -1
#define STDIN 0
#define STDOUT 1
#define STDERR 2
#define INPUT 0
#define OUTPUT 1
#define CHILD 0
#define PARENT 1
typedef struct prog {
int pid;
int pc[2];
int cp[2];
} prog;
void child (prog *run, char *runthis)
{
close(STDOUT);
dup( run->cp[OUTPUT]);
close(STDIN);
dup(run->pc[INPUT]);
close(run->pc[OUTPUT]);
close(run->cp[INPUT]);
execlp (runthis, NULL);
printf ("ERROR!\n");
exit(1);
}
void write_to_child (prog *run, char *writethis)
{
write (run->pc[OUTPUT], writethis, strlen (writethis));
}
prog *runthis (char *runthis)
{
char ch;
int outcount;
prog *run;
run = (prog *) malloc (sizeof (run));
if( pipe(run->pc) < 0) {
perror("Can't make pipe");
exit(1);
}
if( pipe(run->cp) < 0) {
perror("Can't make pipe");
exit(1);
}
switch( run->pid = fork() ) {
case FAIL:
perror("Can't fork");
exit(1);
case CHILD:
child (run, runthis);
default:
return run;
}
return run;
}
void stoprunning (prog *run)
{
char ch;
close(run->pc[OUTPUT]);
close(run->cp[OUTPUT]);
printf ("Closing!\n");
while( read(run->cp[INPUT], &ch, 1) == 1)
write(STDOUT, &ch, 1);
printf ("Finished!\n");
}
int main(void)
{
prog *a, *b;
a = runthis ("/root/mp3/musidab/src/test.awk");
b = runthis ("/root/mp3/musidab/src/test.awk");
write_to_child (a, "testa.mp3");
write_to_child (b, "testb.mp3");
printf ("Running!\n");
stoprunning (a);
sleep (5);
return 0;
}
--- The software end ---
More information about the linuxCprogramming
mailing list