www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - rawRead from Pipe segfaults

reply kdevel <kdevel vogtner.de> writes:
In order to watch out for lost bytes in a pipe I encountered this 
segfault.
It seems that the readEnd is already closed when rawRead = fread 
is
called (uncomment the eof line).

How do I keep the pipe open?

```piperawreadsegfault.d (linux)
import std.stdio;
import std.process;

void main ()
{
    auto dev_zero = File ("/dev/zero", "r");
    auto dev_null = File ("/dev/null", "w");
    auto p = pipe ();
    auto proc1 = spawnProcess (["dd", "bs=4096", "count=2"],
       dev_zero, p.writeEnd);
    auto proc2 = spawnProcess (["dd", "bs=4096", "count=1"],
       p.readEnd, dev_null);
    auto res2 = wait (proc2);
    auto res1 = wait (proc1);
    stderr.writeln ("res1 = ", res1, ", res2 = ", res2);
//  stderr.writeln (p.readEnd.eof);
    ubyte [1] u;
    auto n = p.readEnd.rawRead (u);
}
```

$ dmd -g piperawreadsegfault
$ gdb ./piperawreadsegfault
(gdb) r
Starting program: /tmp/k/piperawreadsegfault
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".
2+0 records in
2+0 records out
8192 bytes (8.2 kB) copied, 2.487e-05 s, 329 MB/s
1+0 records in
1+0 records out
4096 bytes (4.1 kB) copied, 2.0234e-05 s, 202 MB/s
res1 = 0, res2 = 0

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7054f99 in fread () from /lib64/libc.so.6
(gdb) bt


[...]/dmd2/linux/bin64/../../src/phobos/std/stdio.d:4383

     at [...]/dmd2/linux/bin64/../../src/phobos/std/stdio.d:1036

[...]
Mar 17 2021
next sibling parent reply Imperatorn <johan_forsberg_86 hotmail.com> writes:
On Wednesday, 17 March 2021 at 23:08:07 UTC, kdevel wrote:
 In order to watch out for lost bytes in a pipe I encountered 
 this segfault.
 It seems that the readEnd is already closed when rawRead = 
 fread is
 called (uncomment the eof line).

 [...]
Have you tried "scope(exit) wait(" instead?
Mar 18 2021
parent kdevel <kdevel vogtner.de> writes:
On Thursday, 18 March 2021 at 07:55:01 UTC, Imperatorn wrote:
[...]
 Have you tried "scope(exit) wait(" instead?
Yes. Does not make a difference. For the segfault I have filed Issue 21728
Mar 18 2021
prev sibling parent kdevel <kdevel vogtner.de> writes:
On Wednesday, 17 March 2021 at 23:08:07 UTC, kdevel wrote:
[...]
 How do I keep the pipe open?
Having the readEnd and writeEnd closed in the parent is usually the right thing to to. spawnProcess closes the ends which is documented: | Note that if you pass a File object that is not one of the standard | input/output/error streams of the parent process, that stream will | by default be closed in the parent process when this function returns. | See the Config documentation below for information about how to disable | this behaviour. [1] [1] https://dlang.org/phobos/std_process.html#spawnProcess
Mar 18 2021