This question already has answers here:
Why is printf before exevp not running?
                                
                                    (1个答案)
                                
                        
                        
                            Prints before execl is not visible in output
                                
                                    (1个答案)
                                
                        
                                2年前关闭。
            
                    
该程序执行两件事:
1)复制shell的动作
2)将用户输入记录到tmp.log文件中

这里的问题是在我的子进程中,printf(“ ABC”);什么也没做。
输出日志文件可以正常工作,但不会打印。

为什么这样表现呢?

我知道execvp应该替换当前进程,但这不能解释为什么它将执行输出而不执行打印。
我看到了以下链接,但这不能回答我的问题。
exevp skips over all code until wait call in c

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

void execute(char *user_input)
{
    pid_t pid;
    int state_loc;
    if( (pid = fork()) == -1){
      printf("fork failed\n");
      exit(1);
    }
    else if(pid == 0){

      FILE *f;
      //open the file and append. Create if not there.
      f = fopen("tmp.log", "a+");
      if (f == NULL) { printf("Something is wrong");}

      struct tm *p;
      struct tm buf;
      char timestring[100];
      time_t ltime = time(NULL);
      if (NULL != (p=localtime_r(&ltime, &buf))){
        strftime(timestring, sizeof(timestring),"** %c: ", p);
        fprintf(f, "%s %s \n", timestring, user_input);
      }
      fclose(f);

      char* separator = " ";
      char* argv[64];
      int argc = 0;
      char* tmp;
      argv[argc] = strtok_r(user_input, separator, &tmp);
      while( argv[argc] != NULL){
        argc+=1;
        argv[argc] = strtok_r(NULL, separator, &tmp);
      }

      printf("ABC"); //why doesn't this print??

      execvp(argv[0],argv);
    }
    else{
      wait(&state_loc);
    }
}


int main ()
{
  while(1)
  {
    char user_input[1024];
    printf("recsh>> ");
    //empty the buffer right scanf
    scanf("%[^\n]", user_input);
    //calls each character in the user input, repeat until it reaches the terminating \n
    while( getchar() != '\n');
    if(strcmp(user_input, "exit") == 0){
      printf("Exiting\n");
      break;
    }
    else{
      execute(user_input);
    }
  }
  return 0;
}

最佳答案

printf的调用在子对象中调用execvp之前执行。

由于默认情况下stdoutline-buffered,并且打印的文本不构成一行(因为没有新的行字符),因此将其保留在输出缓冲区中。当映像由execvp替换时,该输出缓冲区与原始可执行文件的其余部分一起消失。

道德:请始终以换行符(\n)终止输出。

关于c - execvp跳过C语言中的证书代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50436394/

10-15 12:16