exec函数族如何返回?

sh/bash/dash/ksh/zsh等Shell脚本
回复
Travelinglight
帖子: 7
注册时间: 2014-07-08 21:13
系统: ubuntu 14.04

exec函数族如何返回?

#1

帖子 Travelinglight » 2014-07-15 17:18

linux c中,exec函数族执行成功则不返回,但是如果我想要他返回该怎么做?
例如下段程序:
#include <unistd.h>
int main()
{
char *arg[] = {"ps","-ef",NULL};
execl("/bin/ls","ls","-l",NULL);
execvp("ps",arg);
return 0;
}
运行的时候只会打出ls -l的信息,而ps命令被忽略。如果我想要两个命令都得到执行,怎样在execl执行完毕后返回?
头像
懒蜗牛Gentoo
论坛版主
帖子: 7362
注册时间: 2007-03-02 17:36
系统: Linux Mint

Re: exec函数族如何返回?

#2

帖子 懒蜗牛Gentoo » 2014-07-15 18:50

fork出一个进程再exec,或者直接用sysyem()
虽然世上没有完美的东西,但这并不影响我们追求完美,因为只有偏执狂才TMD能成功。
10.04新手入门——笨兔兔讲述自己的故事
头像
懒蜗牛Gentoo
论坛版主
帖子: 7362
注册时间: 2007-03-02 17:36
系统: Linux Mint

Re: exec函数族如何返回?

#3

帖子 懒蜗牛Gentoo » 2014-07-15 18:50

错了,是system
虽然世上没有完美的东西,但这并不影响我们追求完美,因为只有偏执狂才TMD能成功。
10.04新手入门——笨兔兔讲述自己的故事
头像
astolia
论坛版主
帖子: 6703
注册时间: 2008-09-18 13:11

Re: exec函数族如何返回?

#4

帖子 astolia » 2014-07-16 22:48

exec不会返回,只能fork后,在子进程中exec,父进程用wait等待子进程结束

代码: 全选

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
int main(int argc,char **argv)
{
	pid_t pid = fork();
	int status;
	if (pid == 0) {
		execlp("find", "find", "/home", NULL);
	} else {
		wait(&status);
		if (WIFEXITED(status)) {
			printf("exits with status %d\n", WEXITSTATUS(status));
		} else if (WIFSIGNALED(status)) {
			printf("killed by signal %d\n", WTERMSIG(status));
		}
	}
	return 0;
}
Travelinglight
帖子: 7
注册时间: 2014-07-08 21:13
系统: ubuntu 14.04

Re: exec函数族如何返回?

#5

帖子 Travelinglight » 2014-07-17 16:59

谢谢,也只好开子进程了
回复