I'm trying to make a program that will simulate unnamed pipes, exactly as is possible to do in the terminal in Ubuntu. The program recieves file names and commands to execute for each file. I want to string the programs' input/output through pipes such that the first program's input will be std.in, and its' output will be the second program's input and so forth. Here's what I have so far:
void np_exec(char* cmd, char** argv)
{
while(*(++argv) != NULL)
{
int pid = fork(); //parent executes
if(pid < 0)
{
printf("Error forking")
exit(1);
}
if(pid != 0) // parent
if (execvp(cmd, *argv) == -1)
perror("execvp failed");
//somewhere here i want to pipe input to output
}
}
int main(int argc, char** argv)
{
assert(strcmp(argv[argc-1], "-"));
int i;
for (i = 1; i < argc; ++i) {
if (!strcmp(argv[i], "-"))
{
argv[i] = NULL;
np_exec(argv[1], &argv[1]);
argv = &argv[i];
argc -= i;
i = 0;
}
}
char* args[argc];
args[argc-1] = NULL;
for (i = 1; i < argc; ++i) {
args[i-1] = argv[i];
}
if (execvp(args[0], args) == -1)
perror("execvp failed");
return;
}
}
As you can see, I'm struggling with the pipe implementation. Also, is there a way to test if this program works? Is there a command to write to a file (which will then hopefully carry on to the others?)