#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int rc = fork();
if (rc < 0)
{
printf("fork failed\n");
exit(1);
}
else if (rc == 0)
{
close(STDOUT_FILENO);
int ret = open("./out.log", O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU);
if (ret == -1)
{
printf("Failed to open file for stdout redirection\n");
exit(1);
}
char *myargs[2];
myargs[0] = strdup("ls"); // execute ls command
myargs[1] = NULL;
int status = execvp(myargs[0], myargs);
if (status == -1)
{
printf("execvp: failed");
exit(1);
}
printf("Child: Finished\n");
}
else
{
wait(NULL);
printf("Parent: Finished\n");
}
return 0;
}
Asked
Active
Viewed 144 times
0

WhozCraig
- 65,258
- 11
- 75
- 141
-
[How do I format my code blocks?](https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks) – mkrieger1 Feb 12 '22 at 22:59
-
1If you mean `printf("Child: Finished\n");`, its because `execvp` succeeded, and thereafter *replaced* the current process. [Read the documentation](https://linux.die.net/man/3/execvp). E.g., there is no spoon. – WhozCraig Feb 12 '22 at 23:06
-
To get the child _program_ (what is executed by `execvp`) to output to the target file (e.g. `out.log`), just before the `execvp` we need to attach `stdout` for the program to the file. So, we need to do: `dup2(ret,STDOUT_FILENO); close(ret);` – Craig Estey Feb 13 '22 at 00:32