第五周 加分题-mybash的实现
使用fork,exec,wait实现mybash
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#define DELAY 2
void child_code(int delay,char *arglist[3])
{
printf("child %d here will sleep for %d seconds
",getpid(),delay);
sleep(delay);
execvp("who",arglist);
printf("child done. about to exit
");
exit(17);
}
void parent_code (int childpid)
{
int wait_rv=0;
wait_rv = wait(NULL);
printf("done waiting %d .wait returned :%d
",childpid,wait_rv);
}
int main()
{
char s1[5],s2[5];
scanf("%s%s",s1,s2);
char *arglist[3];
// strcpy(arglist[0],s1);
// strcpy(arglist[1],s2);
arglist[0]="who";
arglist[1]="-a";
arglist[2]=0;
printf("%s",arglist[2]);
int newpid;
printf("before:mypid is %d
",getpid());
if((newpid = fork())==-1)
perror("fork");
else if(newpid==0)
child_code(DELAY,arglist);
else parent_code(newpid);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#define DELAY 2
void child_code(int delay,char *arglist[3])
{
printf("child %d here will sleep for %d seconds
",getpid(),delay);
sleep(delay);
execvp("ls",arglist);
printf("child done. about to exit
");
exit(17);
}
void parent_code (int childpid)
{
int wait_rv=0;
wait_rv = wait(NULL);
printf("done waiting %d .wait returned :%d
",childpid,wait_rv);
}
int main()
{
char s1[5],s2[5];
scanf("%s%s",s1,s2);
char *arglist[3];
// strcpy(arglist[0],s1);
// strcpy(arglist[1],s2);
arglist[0]="ls";
arglist[1]="-a";
arglist[2]=0;
printf("%s",arglist[2]);
int newpid;
printf("before:mypid is %d
",getpid());
if((newpid = fork())==-1)
perror("fork");
else if(newpid==0)
child_code(DELAY,arglist);
else parent_code(newpid);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#define DELAY 2
void child_code(int delay,char *arglist[3])
{
printf("child %d here will sleep for %d seconds
",getpid(),delay);
sleep(delay);
execvp("ls",arglist);
printf("child done. about to exit
");
exit(17);
}
void parent_code (int childpid)
{
int wait_rv=0;
wait_rv = wait(NULL);
printf("done waiting %d .wait returned :%d
",childpid,wait_rv);
}
int main()
{
char s1[5],s2[5];
scanf("%s%s",s1,s2);
char *arglist[3];
// strcpy(arglist[0],s1);
// strcpy(arglist[1],s2);
arglist[0]="ls";
arglist[1]="-l";
arglist[2]=0;
printf("%s",arglist[2]);
int newpid;
printf("before:mypid is %d
",getpid());
if((newpid = fork())==-1)
perror("fork");
else if(newpid==0)
child_code(DELAY,arglist);
else parent_code(newpid);
return 0;
}
实现结果截图