【问题标题】:(Executing a built in program in UNIX (C)(在 UNIX (C) 中执行内置程序
【发布时间】:2023-04-07 16:29:01
【问题描述】:
 #include<stdio.h>
    #include<unistd.h>
    #include<stdlib.h>

    int main(int argc,char *argv[],char *envp[])
    {
        int pid;
        int id;
        pid=fork();
        if(pid<0)
        {
            printf("\n Error ");
            exit(1);
        }
        else if(pid==0)                         //Child process
        {
        execve("a",argv,envp);  //Problem is in here
            printf("\n Pid of child process is %d ",getpid());  //Finds the id of the child process
        exit(0);
        }
        else                                //Parent process
        {
    wait(3);
    printf("\n Pid of parent process is %d ",getpid());
            exit(1);
        }

    }

我正在尝试在 UNIX 中执行一个名为 a 的程序,但它不起作用可能是因为我使用了错误的 exec 命令或程序 a 在不同的目录中,但我不确定。当我从终端执行它时,它给出我是子进程和父进程的 ID,但没有通知我有关程序的信息。

【问题讨论】:

  • 您是否阅读过您调用的任何函数的手册页?
  • 如果你运行这段代码会发生什么,会返回错误或者只是不执行预期的结果?
  • 如果 printf 调用正在执行,则某些内容是 FUed。你检查过errno的值吗?打过 strerror 电话了吗?
  • 它给了我子进程调用和父进程调用的 id。我知道我的程序在当前状态下没有返回整数,但在最新版本的 Ubuntu 中可能不需要它。这没有任何意义,但我找不到更好的解释。退出语句可能是这种情况

标签: c linux unix operating-system exec


【解决方案1】:

它对我有用。我不得不更改呼叫以等待:

int retStat;
wait(&retStat);

因为 wait 真的想返回一个值,没有它程序就崩溃了。您是否检查了您的 a 程序是否在您的路径中,或者您是否在 exec 调用中包含了该路径?

【讨论】:

  • 原来是因为目录不同。似乎在较新版本的 Ubuntu 中,当您有退出语句时,您不需要返回整数值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多