[New-bugs-announce] [issue40299] os.dup seems broken with execvp (LINUX)

krsna report at bugs.python.org
Thu Apr 16 04:58:09 EDT 2020


New submission from krsna <bhrt_k at yahoo.com>:

---CODE---
import os
path = "file.txt"
  
fd = os.open(path, os.O_WRONLY) 
  
os.close(1) #STDOUT
os.dup(fd)
pid = os.fork()

if pid == 0:
    args = "ls -l".split() 
    os.execvp(args[0], args)
else:
    os.waitpid(pid, 0)
    print('Done from Parent')
--- END CODE ---

Running this with python
```
> python -V
Python 3.8.2
```
I get the following:
```
> echo"" > file.txt && python example.py && cat file.txt 
ls: write error: Bad file descriptor
Done from Parent

```
Running the same with micropython:
```
> echo"">file.txt && micropython me && cat file.txt 
total 76
drwxr-xr-x 2 user user  4096 Apr  5 15:29 Desktop
drwxr-xr-x 2 user user  4096 Apr  5 15:29 Documents
drwxr-xr-x 2 user user  4096 Apr 13 18:22 Downloads
drwxr-xr-x 2 user user  4096 Apr  5 15:29 Music
drwxr-xr-x 2 user user  4096 Apr 12 11:16 Pictures
drwxr-xr-x 2 user user  4096 Apr  5 15:29 Public
drwxr-xr-x 2 user user  4096 Apr  5 15:29 Templates
drwxr-xr-x 2 user user  4096 Apr  5 15:29 Videos
-rw-rw-r-- 1 user user   244 Apr 15 22:02 example.py
Done from Parent
```
With the follow C which is almost a 1:1 to the CODE segment above
```
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, const char *argv[])
{
    int fd = open("file.txt", O_WRONLY);

	close(1);
	dup(fd);
	
    if (fork() == 0) {
    	char *cmd = "ls";
		char *argv[3];
		argv[0] = "ls";
		argv[1] = "-l";
		argv[2] = NULL;
  		execvp(cmd, argv);
	} else {
  		wait(0);
  		close(fd);

	    puts("Done from Parent");
	}

    return 0;
}
```
I get the same output as micropython example above
```
> echo"">file.txt && gcc ccc.c && ./a.out && cat file.txt 
total 76
drwxr-xr-x 2 user user  4096 Apr  5 15:29 Desktop
drwxr-xr-x 2 user user  4096 Apr  5 15:29 Documents
drwxr-xr-x 2 user user  4096 Apr 13 18:22 Downloads
drwxr-xr-x 2 user user  4096 Apr  5 15:29 Music
drwxr-xr-x 2 user user  4096 Apr 12 11:16 Pictures
drwxr-xr-x 2 user user  4096 Apr  5 15:29 Public
drwxr-xr-x 2 user user  4096 Apr  5 15:29 Templates
drwxr-xr-x 2 user user  4096 Apr  5 15:29 Videos
-rwxrwxr-x 1 user user 18904 Apr 15 22:53 a.out
-rw-rw-r-- 1 user user   395 Apr 15 22:50 ccc.c
-rw-rw-r-- 1 user user   244 Apr 15 22:02 example.py
Done from Parent
```
I tried looking around for the code of `dup` in cpython to compare, but could only find `dup2.c`.

----------
components: Library (Lib)
messages: 366587
nosy: krsna
priority: normal
severity: normal
status: open
title: os.dup seems broken with execvp (LINUX)
type: behavior
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue40299>
_______________________________________


More information about the New-bugs-announce mailing list