Hey guys,
I have to make a C program that simulates this command :
cat (files here) | sort > file.txt
So, I start and create a pipe. Then create the first child. This first child will execute the Cat through the pipe. Then create a second child that will execute sort, with input from pipe. And redirect output to the file.
So, I have this fragment of code, but the program doesn't execute the Sort and it shows me the error message instead.
..... variables here ....
if (pipe(tub) < 0) panic("Creaci� pipe"); /* pipe creation */
switch (fork()) /* First child will exec Cat */
{
case -1: panic("Fork 1");
case 0:
close(1); dup(tub[1]);
close(tub[0]); close(tub[1]);
arg_list[0] = "cat"; /* Input files for Cat */
for (p=0; p<Nfitxers; p++) {
pid = Pids[p];
sprintf(s, "%d_Winners.txt", pid);
arg_list[p+1]= strdup(s);
}
arg_list[Nfitxers]= NULL;
execv("/bin/cat", arg_list); /* Execute Cat here */
panic("Executant execv cat");
default:
break;
}
switch (fork()) /* Second child execut Sort */
{
case -1: panic("Fork 2");
case 0:
close(0); dup(tub[0]);
close(tub[0]);
/* Creating Output file here */
if ((dest = open("Winners.txt", O_WRONLY|O_TRUNC|O_CREAT, 0600))<0) {
panic("Creaci� del fitxer dest�"); }
dup2(dest,STDOUT_FILENO); /* Redirect output to file */
dup2(dest,STDERR_FILENO);
close(dest);
execl( "sort" , "sort", NULL ); /* Executing sort */
panic("Executant execl sort");
default:
break;
}
close(tub[0]);
close(tub[1]);
wait(&st1);
wait(&st2);