分页: 1 / 1

exec函数族如何返回?

发表于 : 2014-07-15 17:18
Travelinglight
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执行完毕后返回?

Re: exec函数族如何返回?

发表于 : 2014-07-15 18:50
懒蜗牛Gentoo
fork出一个进程再exec,或者直接用sysyem()

Re: exec函数族如何返回?

发表于 : 2014-07-15 18:50
懒蜗牛Gentoo
错了,是system

Re: exec函数族如何返回?

发表于 : 2014-07-16 22:48
astolia
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;
}

Re: exec函数族如何返回?

发表于 : 2014-07-17 16:59
Travelinglight
谢谢,也只好开子进程了