gpt4 book ai didi

c - 使用文本解释器和 execl 打印 agruments

转载 作者:太空宇宙 更新时间:2023-11-04 04:43:34 26 4
gpt4 key购买 nike

我正在尝试使用执行文本解释器的 execl 函数打印命令行参数,但我无法打印第一个参数。

这是我的主程序

    #include<unistd.h>
#include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>

int main(int argc,char *argv[])
{
pid_t pid;
if((pid=fork())<0)
printf("error\n");
else if(pid==0)
if((execl("textinterpreter","this","is","usp","lab",(char*)0))<0)
perror("error in execl\n");

if(waitpid(pid,NULL,0) !=pid)
printf("error1\n");
system("ls > list");
return 0;
}

这是我的文本解释器文件

      #!/home/chirag/echoarg1 my1

这是我的echoarg1.c文件

     #include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
main(int argc,char *argv[])
{
int i;
for(i=0;i<argc;i++)
printf("argv[%d]=%s\n",i,argv[i]);
}

我得到的输出是

        argv[0]=/home/chirag/echoarg1
argv[1]=my1
argv[2]=textinterpreter
argv[3]=is
argv[4]=usp
argv[5]=lab

预期输出在哪里

        argv[0]=/home/chirag/echoarg1
argv[1]=my1
argv[2]=textinterpreter
argv[3]=this
argv[4]=is
argv[5]=usp
argv[6]=lab

谁能指出错误

最佳答案

来自 execl 手册页:

int execl(const char *path, const char arg0, ... /, (char *)0 */);

The initial argument for these functions is the pathname of a file which is to be executed.

The const char *arg0 and subsequent ellipses in the execl(), execlp(), and execle() functions can be thought of as arg0, arg1, ..., argn. Together they describe a list of one or more pointers to null-terminated strings that represent the argument list available to the executed program. The first argument, by convention, should point to the file name associated with the file being executed. The list of arguments must be terminated by a NULL pointer.


所以在你的行中:

  if((execl("textinterpreter","this","is","usp","lab",(char*)0))<0)

“textinterpreter”是要执行的文件的路径,但 execl 需要下一个参数 arg0,以“指向与正在执行的文件关联的文件名”。

换句话说,它应该看起来更像:

  if((execl("textinterpreter","textinterpreter","this","is","usp","lab",(char*)0))<0)

通常 execl 的前两个参数可能是相同的,但它允许您灵活地指定一个参数用于查找要执行的文件,另一个参数作为 argv[0] 传递。


作为实验,尝试更改您的 execl 以像这样直接调用 echoarg1:

if((execl("echoarg1","FAKEPATH","this","is","usp","lab",(char*)0))<0)

您应该看到如下输出:

argv[0]=FAKEPATH
argv[1]=this
argv[2]=is
argv[3]=usp
argv[4]=lab

在您的示例中,由于 bash 解释器如何处理您的“textinterpreter”脚本,它似乎显示“this”而不是“textinterpreter”。 bash 解释器的作用如下:

  • 获取 hash-bang 行并运行 /home/chirag/echoarg1
  • 传递 argv[0]=/home/chirag/echoarg1
  • 将 hashbang 行的其余部分作为附加参数传递给它(在本例中只是 argv[1]=my1)
  • 因为它附加了原始的 argv 列表,它似乎使用可执行路径(“textinterpreter”)而不是实际的 argv[0](“this”),然后继续使用 argv[1](“is”)和其余的...

关于c - 使用文本解释器和 execl 打印 agruments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23582343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com