- 论坛徽章:
- 0
|
system 函数和有同等机能的函数(mysystem)的示例。
execlp(execvp,..)函数一实行参数的命令和指定参数就将执行,但是执行后,相应程序将终止。
如果想在其执行后,仍继续进行程序处理动作,就要通过fork生成子进程,在那个子进程内执行execlp等命令。execlp函数执行结束后,即使子进程终了后,其父进程仍然能够继续执行相应处理。
execlp 函数中,用通常的shell执行pipe和Redirection处理( | etc.)和通过正规表现(? * etc.)不能进行复杂的处理.如要进行复杂的处理,通过shell command(/bin/sh etc.)来执行. 例:
execlp("/bin/sh","/bin/sh","-c","ls | wc > output.txt",NULL);
例如,mysystem()函数的执行例和根据mysystem()函数的执行结果(exit status)发生分歧处理的例子。
system函数(fork,execlp)(list_76.c)
#include stdio.h>
#include stdlib.h>
#include sys/types.h>
#include sys/wait.h>
int mysystem(char* cmd)
{
int child,status;
if ((child = fork()) 0) {
perror("fork");
return EXIT_FAILURE;
}
if(child == 0){
execlp("/bin/sh","/bin/sh","-c",cmd,NULL);
return EXIT_FAILURE;
} else {
if(wait(&status) 0) {
perror("wait");
exit(1);
}
}
return status;
}
int main(int argc,char* argv[])
{
int status;
char cmd[256];
if(argc 4) {
printf("usage: %s \"test-rule\" \"true command\" \"false command\"\n",argv[0]);
return 0;
}
printf("**test of mysystem\n");
mysystem("cat list_76.c | wc");
printf("**execute shell rule\n");
sprintf(cmd,"test %s;",argv[1]);
status = mysystem(cmd);
if(status) mysystem(argv[3]);
else mysystem(argv[2]);
return 0;
}
执行结果
Gami[178]% ./list_76.exe
usage: ./list_76.exe "test-rule" "true command" "false command"
Gami[179]% ./list_76.exe "-f makefile" "head makefile" "ls"
**test of mysystem
43 90 840
**execute shell rule --> true 的执行[存在 makefile ]
SRC = list_76
OBJS = $(SRC).o
COMP = gcc
FLAG = -lm -Wall
LANG = c
all: $(OBJS)
$(COMP) -o $(SRC) $(OBJS) $(FLAG)
./$(SRC)
Gami[180]% ./list_76.exe "-d folder" "head makefile" "ls -F"
**test of mysystem
43 90 840
**execute shell rule --> false 的执行[名叫folder 的文件夹不存在]
makefile misc/ list_76.c list_76.exe* list_76.o
Gami[181]%
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/98822/showart_1992370.html |
|