c - 为什么我用 fgets() 读取的命令不适用于 execlp(),但硬编码的相同命令却能正常工作?

标签 c linux

我有一个 C 程序,我在其中读取用户输入并在子进程中运行它。但是不知何故 execlp 没有在控制台上打印任何东西。当我使用 execlp("ls","ls", NULL) 时,它工作正常但使用用户输入不会在控制台上打印任何内容。

代码

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
    char str[1024];
    printf("This program forks a Unix process and execute a command string.\n");
    printf("Enter command string:");
    fgets(str,sizeof(str),stdin);

    printf("entered string %s",str);
    int BeforeparentID=getpid();

    printf("\nParent process ID before fork():%d",BeforeparentID);

    int cid =fork();
    int AfterparentID=getpid();
    printf("\nParent process ID after fork():%d",AfterparentID);
    printf("\nChild process ID afterr fork():%d\n",cid);

    sleep(1);
    if(cid==0){
        execlp(str,str,NULL); //this does not print anything
    }
    else{
        sleep(1);
        waitpid(cid,0,0);
    }
}

示例执行

This program forks a Unix process and execute a command string.
Enter command string:ls
entered string ls

Parent process ID before fork():15368
Parent process ID after fork():15368
Child process ID afterr fork():15369
Parent process ID before fork():15368
Parent process ID after fork():15369
Child process ID afterr fork():0

就是这样;没有目录列表。为什么?

最佳答案

当您输入 ls 时,您发送的不是同一件事。您使用换行符 ('\n') 完成输入,fgets 保持 在输入字符串的尾部。因此,您实际上是在执行:

execlp("ls\n", "ls\n", NULL);

由于您不检查执行 execlp 的结果(很多人不这样做,但它在这里具有教育意义,因为它会指示错误),您看不到问题并简单地假设它有效(我打赌你现在犯的频率要低得多的错误;检查你的返回结果)。

从输入字符串中删除换行符:

char *nl = strrchr(str, '\n');
if (n1)
    *n1 = 0;

然后将它发送到execlp

祝你好运。

关于c - 为什么我用 fgets() 读取的命令不适用于 execlp(),但硬编码的相同命令却能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29711696/

相关文章:

c - C 中的动态链接(使用 dlopen)和 header 包含

使用 libuv 捕获子进程的标准输出

c - malloc 有时起作用,有时不起作用(通用链表)

linux - 如何使用 winscp 控制台将文件从远程 Windows 8 服务器传输到 Linux 服务器

c++ - C++ 在磁盘上的特定位置创建队列

c - 在 MacOS 上构建 mongodb C 驱动程序

c - 如何在我的答案中获得乘号(质因数分解)

linux - 如何在 BASH 中以 DIALOG 形式显示可用 Wifi 网络列表?

linux - 如何创建需要输入root密码才能获得root访问级别的用户

c - 枚举捕获 ALSA 设备并从中捕获