我有以下 C 代码。我想通过调用 execv()
来显示我的文件
但是以下似乎永远行不通。程序终止并弹出提示。
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main(void){
int pid;
if(pid=fork()>0){
//read in from stdin and pass to pipe
}else if(pid==0){
//read from pipe
//write to out.txt
//everything up to here works fine
char* para[]={"less","/Desktop/out.txt"};
execv("/bin/less",para);
}
return 0;
}
最佳答案
(原始代码包含execv("bin/less", para);
。)除非当前目录是根目录,/
, 或者除非有一个程序 less
在子目录中 ./bin/less
,那么您的问题之一是您在可执行文件的名称中可能有拼写错误。假设程序是 /bin/less
而不是 /usr/bin/less
.你甚至可以使用 execvp()
对程序进行基于 PATH 的搜索。
还有一个问题:您需要包含一个空指针来标记参数列表的结尾。
最后,您可以在 execv()
之后打印一条错误消息返回。它返回的事实本身就说明它失败了。
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int main(void)
{
int pid;
if ((pid = fork()) != 0)
{
// read in from stdin and pass to pipe
// Need to test for fork() error here too
}
else
{
// read from pipe
// write to out.txt
// everything up to here works fine
char *para[] = { "/bin/less", "Desktop/out.txt", 0 };
execv(para[0], para);
fprintf(stderr, "Failed to execute %s\n", para[0]);
exit(1);
}
return 0;
}
或者:
char *para[] = { "less", "Desktop/out.txt", 0 };
execvp(para[0], para);
fprintf(stderr, "Failed to execute %s\n", para[0]);
代码中关于管道的注释令人费解,因为除了注释之外没有管道的迹象。就目前而言,less
将读取它被告知要读取的文件。注意 less
如果输出不进入终端,则不会对其输出进行分页。由于我们看不到 I/O 重定向,因此我们必须假设 less
将忽略程序试图写入的任何内容,并且不会将任何数据发送回程序。
关于c - 使用 execv 执行更少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10763935/