【问题标题】:execv waiting for input input instead of executing programexecv 等待输入而不是执行程序
【发布时间】:2016-02-06 19:36:51
【问题描述】:

我有一个名为“test”的程序,它执行另一个名为“hello”的程序。收到所需程序的名称后,我的程序似乎在等待更多输入以显示“hello”程序代码。示例代码的sn-p

#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h> /* for fork */
#include <sys/wait.h> /* for wait */
int main()  {

    char *temp[] = {NULL,NULL,NULL,NULL};
    char  buf[BUFSIZ];
    char s[256];

    while(1) {

        printf("type r at next input\n");
        fgets(buf, sizeof(buf), stdin); 
        strtok(buf, "\n");

        if((strcmp(buf,"r")) == 0) { //if r typed
            printf("run what file : ");
            scanf("%s ",s);

            pid_t i = fork();
            if (i == 0) //we are in child process
            {
                execv(s,temp);
                _exit(1);
            }
            if (i != 0) { //parent
                wait(NULL);
            }
        }
        else
            exit(0);
    }
}

“hello”程序是...

#include<stdio.h>

main(int argc, char* argv[])
{
    printf("\nHello World\n");

}

在 linux 上从 shell 运行的示例是...* 表示我的输入,// 是 cmets

issac@issac-ThinkPad-T440s ~$ ./a.out
type r at next input
*r*
run what file : *hello*
*r*    //i cant proceed unless i type a character so i input *r*?

Hello World    //after ?additional? input it finally displays the "hello" program code
type r at next input    //loops back but program skips my input?
run what file ex ? hello : 

我意识到这可能是一个简单的错误,但我无法弄清楚这有什么问题。我意识到跳过输入的最后一部分可能是由于输入缓冲区中有换行符,但更令人困惑的是为什么在执行“hello”后我的程序等待更多输入来显示结果。

【问题讨论】:

  • 删除scanf 中的尾随空格。应该是:scanf("%s",s);.
  • 有效,但程序在执行 hello 后结束,应循环返回并等待更多输入。有什么想法吗?

标签: c linux exec


【解决方案1】:

要回答您的第一个问题:在 scanf() 中添加一个尾随空格,使其看起来像这样:scanf("%s",s);

回答你的第二个问题:你的问题是你混合了scanf()fgets()。换行符scanf() 使用,并作为新输入传递给下一个(非第一个)fgets。最简单的解决方案是在两个地方都使用fgets

#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h> /* for fork */
#include <sys/wait.h> /* for wait */
#include <string.h>

int main()  {

    char *temp[] = {NULL,NULL,NULL,NULL};
    char  buf[BUFSIZ];
    char s[256];

    while(1) {
        printf("type r at next input\n");
        fgets(buf, sizeof(buf), stdin);
        strtok(buf, "\n");

        if((strcmp(buf,"r")) == 0) { //if r typed
            printf("run what file : ");
            fgets(s, sizeof(s), stdin);
            strtok(s, "\n");
            pid_t i = fork();
            if (i == 0) //we are in child process
                {
                    execv(s,temp);
                    _exit(1);
                }
            if (i != 0) { //parent
                wait(NULL);
            }
        }
        else
            exit(0);
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2021-01-11
    相关资源
    最近更新 更多