C language under linux uses execl to open a file with vim, and there is a magical reading error solution

I think you can use vim by using the execl function. But there was a magical reading error, and the entire terminal crashed.


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
int main()
{
    
       pid_t pid;
    
    pid=fork();

    if(pid==-1){
    
    
        perror("fork error");
        exit(1);
    }
     if(pid==0){
    
    
        //  execl("/bin/ls","/bin/ls","-l",NULL);
        // execl("./a.out","./a.out",NULL);
        //  execlp("ls","ls","-l",NULL);
        close(open("test.c",O_CREAT|O_RDWR|O_APPEND,0644));
        execl("/usr/bin/vim","/usr/bin/vim","test.c",NULL);
        
        //  perror("execl");
        //  exit(1);
    }
     if(pid>0){
    
    
         sleep(1);
        printf("mychild:%d,myid =%d ,myparid=%d\n",pid,getpid(),getppid());
    }
}

Insert picture description here
Netizen's answer: 父进程退出后,子进程就变成了孤儿进程,由init进程收养,成为了后台进程。但此时因为父进程退出,终端的控制权还给了shell,标准输入此时是shell进程在读,但fork的子进程因为继承了父进程的文件描述符,此时vim的标准输入也是指向终端,在终端输入的字符只能由前台进程读取,所以vim出错。上面测试的几个程序只用到了标准输出,所以看不到这个现象
That is, at this time, vim wants to read the data in the terminal, and an error occurs.

If you use execl to execute ls, it will execute output. Think about it, ls is indeed output in the terminal, but the input of vim is more like reading in a new shell.

When I was using myshell today, I suddenly discovered how my myshell can be vim, and found that my parent process is waiting for the child process. Vim is a continuous process, but the above program is sleep, and the parent process exits prematurely. As a result, there is a problem that vim and shell compete for standard input at the same time.

So the parent process wait is over!

Guess you like

Origin blog.csdn.net/adlatereturn/article/details/105452737