TJ Shah
TJ Shah

Reputation: 445

php call system() and write to a named pipe without blocking

I'm have some php code:

<?
$cmd="mkfifo /tmp/myfifo;";
system($cmd);
$cmd="echo 1 > /tmp/myfifo 2>&1 &";
system($cmd);
?>

on an apache server. I want to have the second command not block. According to the info page of system:

If a program is started with this function, in order for it to continue running 
in the background, the output of the program must be redirected to a file or 
another output stream. Failing to do so will cause PHP to hang until the execution 
of the program ends.

But I don't see how to apply that to this situation. I tried

$cmd="echo 1 > /tmp/myfifo > /dev/null 2>&1 &";

But to be honest that seems nonsensical.

EDIT:

My ultimate goal is to write to a fifo that may never be read from, and time out the write after 5 seconds. So, if I can manage to get this command to not block the php executition, I can sleep 5 seconds and then cat /tmp/myfifo > /dev/null 2>&1 to unblock the original write.

Can anyone think of a better way to have my write not hang indefinitely (in neither the background nor the foreground)?

Upvotes: 0

Views: 2175

Answers (3)

Ivana Answer
Ivana Answer

Reputation: 21

If the environment created by system() is bash 4.x or later I believe you could use "coproc" to prevent it from blocking? This works for me in shell scripts. (Or, if it's not executing in bash directly, you could have it call "bash -c ..." )

Upvotes: 2

Xeoncross
Xeoncross

Reputation: 57184

If you need to write to a file (and prevent other processes from writing until you are done), then just use file_put_contents.

<?php
// The new person to add to the file
$person = "John Smith\n";

// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents('/tmp/myfifo', $person, FILE_APPEND | LOCK_EX);

Upvotes: 1

ldiqual
ldiqual

Reputation: 15365

You could use nohup to launch a process in the background:

$ nohup binary arguments
$ man nohup

Upvotes: 0

Related Questions