From a parent process, I am trying to control a child process through standard input/output. I used the following MSDN example to create the child process and redirect its standard input & output : http://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.100%29.aspx
On the parent side I send the same "command" twice using the following code:
const char cmd[] = "test\n";
DWORD written, read;
BOOL success;
success = WriteFile(g_hChildStd_IN_Wr, cmd, sizeof(cmd), &written, NULL);
success = WriteFile(g_hChildStd_IN_Wr, cmd, sizeof(cmd), &written, NULL);
On the child side, I read those commands through a fgets call. The first command is read as expected. But when the second command is sent, the fgets call returns with an empty string and the next fgets call does not return. Here is the child process code:
char *retStrP;
char str[256];
size_t strLen;
retStrP = fgets(str, 256, stdin);
strLen = strlen(str);
if (retStrP != str)
{
char errorStr[256];
int a = feof(stdin);
int b = ferror(stdin);
sprintf(errorStr, "Fgets error, %d %d\n", a, b);
OutputDebugString(errorStr);
}
else if (strLen == 0)
{
char errorStr[256];
int a = feof(stdin);
int b = ferror(stdin);
sprintf(errorStr, "Strlen is 0, %d %d\n", a, b);
OutputDebugString(errorStr);
}
From the previous code, the second call to fgets behaves as follow: the returned pointer is equal to the str buffer but the strlen is 0.
When reading the MSDN fgets documentation ( http://msdn.microsoft.com/en-us/library/c37dh6kf%28v=vs.100%29.aspx ), I don't see any way it could return the pointer to the buffer passed as the first argument with the first buffer's byte being set to 0 (as far as the buffer size is greater than 1). If an error occurs or the end of file is reached, the fgets should return NULL and either feof or ferror should return something not 0.
I suspect something is going wrong with the pipes handling but I can't figure out what... From the parent side, I don't do anything more with the stdin write pipe than sending the same buffer twice. Any idea what could cause such a behaviour?