【问题标题】:printf after execl not showingexecl后的printf没有显示
【发布时间】:2019-11-27 17:25:21
【问题描述】:

我正在测试execl() 函数,但我无法解决如何在运行程序时显示execl() 之后的printf()。我发现它与fflush() 函数有关,尽管我仍然做不到。 这是代码。

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

void main(){
    printf ("Show content from directory /:\n");
    execl( "/bin/ls", "ls", "-l", "/", NULL );
    fprintf (stdout,"End of command: ls -l /\n");
    fflush(stdout);
}

【问题讨论】:

  • 你永远不会从exec*() 调用中返回,除非它失败了。
  • 除非execl() 失败,否则它不会显示。 exec() 系列函数从字面上完全取代了当前进程。请参阅stackoverflow.com/questions/4204915/…(我会让其他人决定这是否与该问题重复。)
  • 你知道execl() 是做什么的吗?你知道它与system() 有多么不同吗? (你可能想要system()。)
  • 如果您不想替换当前进程,请在使用fork() 创建的子进程中调用execl()。然后在父级中使用wait() 等待它完成。

标签: c


【解决方案1】:

来自手册页 https://linux.die.net/man/3/execl

返回值 exec() 函数仅在发生错误时返回。返回值为-1,设置errno表示错误。

如果你真的想使用execl() 而不是system(),那么 您应该像这样更改代码。

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

int main(void){
    printf ("Show content from directory /:\n");

    pid_t p=fork(); // create a child process
    if(p==0) // if we are in the child process
    {
      execl( "/bin/ls", "ls", "-l", "/", NULL ); // replace it with a new program
      perror("execl"); // reaching this line is necessarily a failure
      exit(1); // terminate child process in any case
    }
    waitpid(p, NULL, 0); // wait for child process to terminate

    fprintf (stdout,"End of command: ls -l /\n");
    fflush(stdout);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 2020-08-23
    相关资源
    最近更新 更多