prog3.c

来自「linux 流文件操作」· C语言 代码 · 共 44 行

C
44
字号
#include <stddef.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <sys/wait.h>#include <stdio.h>#define SHELL "/bin/sh"int mainint argc,char *argv[]{	int status1;	pid_t pid1;	char cmd[100];	while(1)	{		printf("please enter the command,and type 'quit' to exit this program:\n");		scanf("%s",cmd);		if(strcmp(cmd,"quit")==0)			break;		pid1=fork();		status1=my_system(cmd,pid1);		printf("my pid is %d,the exit status is %d\n",pid1,status1);	}	return 0;			}int my_system(const char *command,pid_t pid){	int status;	if(pid==0)	{		//child process,execute the command		execl(SHELL,SHELL,"-c",command,NULL);		_exit(EXIT_FAILURE);	}	else if(pid<0)		//fork failed,report failure		status=-1;	else		//parent process,wait the end of child		if(waitpid(pid,&status,0)!=pid)			status=-1;	return status;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?