I'm currently trying to run an ls command in my C code and then pipe the outputted strings to the parent process via a fd.
The problem I'm currently facing is, that I execv the ls command but I don't know how to store the strings (if that is even necessary) and then pipe them to my parent process and execute another command with the given input like I wrote in the comment. Is there also a way to block the ls output to the terminal in my child process?
int main(void)
{
int fd1[2]; // Used to store two ends of first pipe
int fd2[2]; // Used to store two ends of second pipe
pid_t p;
p = fork(); // Now forking to create a child
// Parent process
else if (p > 0)
{
close(fd1[0]); // Close reading end of first pipe
// Wait for child to send the strings
wait(NULL);
close(fd2[1]); // Close writing end of second pipe
// Read strings from child, print it and close
// reading end.
read(fd2[0], "", 100);
close(fd2[0]);
// todo another command like "wc -l" and print the result to the terminal with write
}
// Child process
else
{
close(fd1[1]); // Close writing end of first pipe
// execute ls command and send the strings to the parent
int status;
char *args[2];
args[0] = "/bin/ls"; // first arg is the full path to the executable
args[1] = NULL; // list of args must be NULL terminated
execv( args[0], args ); // child: call execv with the path and the args
// Close both reading ends
close(fd1[0]);
close(fd2[0]);
// write the strings to the parent
write(fd2[1], "", strlen("") + 1);
close(fd2[1]);
exit(0);
}
return EXIT_SUCCESS;
}
I'm sorry if this is a silly question, but I'm very new to forking and using pipes.