第五周 加分题-mybash的实现

第五周 加分题-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\n",getpid(),delay);
	sleep(delay);
	execvp("who",arglist);
	printf("child done. about to exit\n");
	exit(17);
}
void parent_code (int childpid)
{
	int wait_rv=0;
	wait_rv = wait(NULL);
	printf("done waiting %d .wait returned :%d\n",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 \n",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\n",getpid(),delay);
	sleep(delay);
	execvp("ls",arglist);
	printf("child done. about to exit\n");
	exit(17);
}
void parent_code (int childpid)
{
	int wait_rv=0;
	wait_rv = wait(NULL);
	printf("done waiting %d .wait returned :%d\n",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 \n",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\n",getpid(),delay);
	sleep(delay);
	execvp("ls",arglist);
	printf("child done. about to exit\n");
	exit(17);
}
void parent_code (int childpid)
{
	int wait_rv=0;
	wait_rv = wait(NULL);
	printf("done waiting %d .wait returned :%d\n",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 \n",getpid());
	if((newpid = fork())==-1)
		perror("fork");
	else if(newpid==0)
		child_code(DELAY,arglist);
	else parent_code(newpid);
	return 0;
		
}

实现结果截图

image

posted @ 2017-10-20 16:33  田宜楠20155304  阅读(133)  评论(0编辑  收藏  举报