I'm trying to write a program to create 6 children with fork system call that each of them run /bin/ls command with diffrent types of exec() function and when all children finished their works the parent should print out it's pid. still giving wrong output with this code :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
printf("hello world (pid:%d)\n", (int) getpid());
for (int i =0 ; i<6;i++)
{
char *myargs_path = "/bin/ls";
char *myargs_file[2] = {"ls",NULL};
char *myargs_temp[2] = {"done",NULL};
if (fork() == 0)
{
if (i == 0)
{
printf("hello, I am child (pid:%d)\n", (int) getpid());
execl(myargs_path,myargs_path,NULL);
}
if (i == 1)
{
printf("hello, I am child (pid:%d)\n", (int) getpid());
execlp(myargs_file[0],myargs_file[0],NULL);
}
if (i == 2)
{
printf("hello, I am child (pid:%d)\n", (int) getpid());
execle(myargs_path,myargs_path,NULL,myargs_temp);
}
if (i == 3)
{
printf("hello, I am child (pid:%d)\n", (int) getpid());
execv(myargs_path,myargs_path);
}
if (i == 4)
{
printf("hello, I am child (pid:%d)\n", (int) getpid());
execvp(myargs_file[0],myargs_file[0]);
}
if (i == 5)
{
printf("hello, I am child (pid:%d)\n", (int) getpid());
execvpe(myargs_file[0],myargs_file,myargs_temp);
}
}
}
for(int i=0;i<6;i++)
{
int wc = wait(NULL);
printf("hello, I am parent of %d (wc:%d) (pid:%d)\n",wc, wc, (int) getpid());
}
return 0;
}
You have a few incorrect arguments. You want:
switch(i) {
case 0: execl(myargs_path, myargs_path, NULL);
break;
case 1: execlp(myargs_file[0], myargs_file[0], NULL);
break;
case 2: execle(myargs_path, myargs_path, NULL, myargs_temp);
break;
case 3: execv(myargs_path, myargs_file);
break;
case 4: execvp(myargs_file[0], myargs_file);
break;
case 5: execvpe(myargs_file[0], myargs_file, myargs_temp);
break;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.