I have the following code draft.
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf( "usage: %i filename", argc );
pid_t pID = fork();
if (pID == 0) // child
{
// Code only executed by child process
printf("Child PID: %i", pID);
int file = open("/tmp/rtail", O_CREAT | O_WRONLY);
//Now we redirect standard output to the file using dup2
dup2(file,1);
char tmp[30];
sprintf(tmp, "cat `tail -f %s`", argv[1]);
}
else if (pID < 0) // failed to fork
{
printf("Failed to fork");
exit(1);
// Throw exception
}
else // parent
{
}
// Code executed by both parent and child.
return 0;
}
How do I pass command line arguments to a child process? For example, running ./app alch.txt
I want
sprintf(tmp, "cat `tail -f %s`", argv[1]);
to produce
cat `tail -f alch.txt`
in tmp.
The child process then uses execl() to replace the process memory with one from a new file. Notice that progname is given twice to execl(). The first is what execl() will actually try to run, the second is argv[0]. You must provide both or the argument count will be off by one.
Suspends the calling process until any one of its child processes ends. More precisely, wait() suspends the calling process until the system obtains status information on the ended child. If the system already has status information on a completed child process when wait() is called, wait() returns immediately.
There is not really one executing before the other. It is simply that the parent will fork() then wait() for the child to complete. It may even fork several times if you use a piped series of commands for instance.
With a fork(), there are now two processes that are working concurrently. Output can be obtained by using the same code, as used above in exec example. The output shows that the child process is executed earlier than the parent when the parent process was waiting.
How do I pass command line arguments to a child process?
You don't need to do anything special; fork
ensures that each process gets all local variables, including argv
.
Sorry for the trouble, it indeed works fine. My earlier version didn't work for some reason, but apparently I've changed something to make it right. Will run my code before a question next time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With