Chinaunix首页 | 论坛 | 博客
  • 博客访问: 439565
  • 博文数量: 88
  • 博客积分: 2677
  • 博客等级: 少校
  • 技术积分: 893
  • 用 户 组: 普通用户
  • 注册时间: 2009-06-13 08:01
文章分类

全部博文(88)

文章存档

2017年(3)

2016年(1)

2012年(4)

2011年(4)

2010年(57)

2009年(19)

我的朋友

分类: LINUX

2009-07-10 22:40:02

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]%

阅读(2973) | 评论(0) | 转发(0) |
0

上一篇:FORK 中文man

下一篇:IOCTL 中文MAN

给主人留下些什么吧!~~