Reputation: 11
I write this program which must execute mkdir and rmdir, the parent must send argument to child and child execute it.
void main()
{
int r;
int i;
int fd[2];
pipe(fd);
char arg[100];
printf("Please Choose one of the following commands: \n");
printf("1 MKDIR \n");
printf("2 RMDIR \n");
while(1)
{
printf("You choose: \n");
scanf("%d ", &r);
pid_t pid;
pid = fork();
printf("Please enter arguments: ");
scanf("%s ", arg);
write(fd[1],arg,sizeof(arg));
for(i=0;i<4;i++)
{
if(pid==0)
{
switch(r)
{
case 1:
read(fd[0],arg,sizeof(arg));
execl("/bin/mkdir", "MKDIR", arg, NULL);
case 2:
read(fd[0],arg,sizeof(arg));
execl("/bin/rmdir", "RMDIR", arg, NULL);
}
}
break;
}
}
}
The problem is that when I execute it it, I I need to scan r two times, then it repeat please enter the argument twice, and it execute the second argument of r.
Upvotes: 0
Views: 583
Reputation: 409136
Remember that the child process starts executing the code directly after the fork
call, that means that both the parent and child processes will call scanf
. You need to check if you are in the child or parent process directly after the fork
call.
You also need to have a break
statement between the cases in the switch
statement, or else when you do the first case the it will continue and to the second as well.
There is also the problem that the child processes never exit, but continue the endless loop. Once the child process is done it should exit
.
You are also creating lots of "defunct" processes, in that you never wait
for your child processes. You need to call the wait
function (or one of its related functions like waitpid
) to "reap" the child. Otherwise the process will still be existing even even if it's in a state where it's paused.
Upvotes: 1