If I input this command onto a Linux terminal, and lets say ./loop is a C program that I've compiled. (./loop is just a program that prints 'hello world' for n amount of times)
$time ./loop 8
I'm looking to take this command line input of ./loop 8
, and pass the calling of it to a new child process instead of letting the original process run it. And hence the process time
would have to wait for the termination of the child process (ie. ./loop).
I'm still very new to the entirity of fork() and exec() (and C language programming as well :b) so was wondering how could I take the command line argument and start the command as a new child process?
EDIT: is this the possible solution?
int main(int argc, char *argv[]) {
pid_t pid = fork()
if (pid < 0)
{
return -1;
}
else if(pid = 0 ){
printf("i am a child process, with pid: %d\n", (int)getpid());
int execvp(char *argv[0], char *argv[1]);
exit(0);
}
else{
printf("i am parent ");
int status ;
pid_t child_pid;
child_pid = wait4(pid, &status, 0)
//print the exit statment
//prirnt the exit stats (ie. run time, etc.)
}
}
CodePudding user response:
If I understand you right, you're looking for something like this (which doesn't do anything with the rusage
yet, but feel free to). (Also, there are no bounds checks. Be careful.)
The important thing to understand is that the child process becomes the process executed by execvp
and doesn't start a new child of its own.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
pid_t pid = fork();
if (pid < 0) {
perror("fork failed");
return 1;
} else if (pid == 0) {
printf("i am a child process, with pid: %d\n", (int)getpid());
execvp(argv[1], argv 1);
// This can only be reached if execvp returns (i.e. fails to exec)
perror("execvp failed");
exit(123);
}
printf("i am parent of %d\n", pid);
int status;
struct rusage ru;
pid_t child_pid = wait4(pid, &status, 0, &ru);
if(child_pid < 0) {
perror("wait4 failed");
} else {
printf("child exited with %d\n", status);
}
exit(0);
}
Example:
$ clang -o forky -Wall forky.c
$ ./forky /bin/echo hello
i am parent of 11522
i am a child process, with pid: 11522
hello
child exited with 0
$