File: PipeProcess.cpp

package info (click to toggle)
sofa-framework 1.0~beta4-4
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 88,224 kB
  • ctags: 26,759
  • sloc: cpp: 151,113; ansic: 2,387; xml: 581; sh: 431; makefile: 101
file content (364 lines) | stat: -rw-r--r-- 9,872 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                              SOFA :: Framework                              *
*                                                                             *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza,  *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "PipeProcess.h"

#ifdef WIN32
#include <windows.h>
#include <process.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
typedef int ssize_t;
typedef HANDLE fd_t;
typedef SOCKET socket_t;
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
typedef int fd_t;
typedef int socket_t;
#endif

#include <cstring>
#include <iostream>
#include <sstream>

#define BUFSIZE (64*1024-1)
#define STEPSIZE (1024)
//#define STEPSIZE BUFSIZE

namespace sofa
{

namespace helper
{

namespace system
{

PipeProcess::PipeProcess()
{
}

PipeProcess::~PipeProcess()
{
}
	/**   File as Stdin for windows does not work (yet)
	  *   So the filename must be given into the args vector
	  *   and argument filenameStdin is currently ignored
	  */

bool PipeProcess::executeProcess(const std::string &command,  const std::vector<std::string> &args, const std::string &filenameStdin, std::string & outString, std::string & errorString)
{
	std::string fileIN = filenameStdin;

	//Remove this line below when Windows will be able to read file as stdin
	fileIN = "";
	
	fd_t fds[2][2];
    
    //char eol = '\n';
    char** cargs;
    std::string newCommand(command);
    
    cargs = new char* [args.size()+2];
    cargs[0] = (char*)command.c_str();
    for (unsigned int i=1 ; i< args.size() + 1 ; i++)
    	cargs[i] = (char*)args[i-1].c_str();
    cargs[args.size() + 1] = NULL;

    fd_t fdin;
    fd_t fdout;
    fd_t fderr;
    
#ifdef WIN32
	fdin = GetStdHandle(STD_INPUT_HANDLE);
	
	fdout = GetStdHandle(STD_OUTPUT_HANDLE);
	fderr = GetStdHandle(STD_ERROR_HANDLE);
	
	for (unsigned int i=0 ; i< args.size() ; i++)
		newCommand += " " + args[i];
	
#else
	fdin = 0;
	fdout = 1;
	fderr = 2;
#endif

    outString = "";
    errorString = "";
    std::stringstream outStream;
    std::stringstream errorStream;

#ifdef WIN32
    SECURITY_ATTRIBUTES saAttr;
    // Set the bInheritHandle flag so pipe handles are inherited. 
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
    saAttr.bInheritHandle = TRUE; 
    saAttr.lpSecurityDescriptor = NULL;
    if (!CreatePipe(&fds[0][0],&fds[0][1],&saAttr,0) || !CreatePipe(&fds[1][0],&fds[1][1],&saAttr,0))
#else
    if (pipe(fds[0]) || pipe(fds[1]))
#endif
	{
		std::cerr << "pipe failed."<<std::endl;
		return false;
	}
#ifdef WIN32
    HANDLE hFile = 0;
    if (fileIN != "")
    	hFile = CreateFileA( (fileIN.c_str()),
						GENERIC_READ,
					    FILE_SHARE_READ,
					    NULL,
					    OPEN_EXISTING,
					    FILE_ATTRIBUTE_NORMAL,
					    NULL);
    
	if (hFile == INVALID_HANDLE_VALUE) {
		std::cerr<<"failed to open file for stdin\n";
	}

    // Ensure that the read handle to the child process's pipe for STDOUT is not inherited.
    SetHandleInformation( fds[0][0], HANDLE_FLAG_INHERIT, 0);
    SetHandleInformation( fds[1][0], HANDLE_FLAG_INHERIT, 0);
    SetHandleInformation( fdin, HANDLE_FLAG_INHERIT, 1);
    PROCESS_INFORMATION piProcInfo; 
    STARTUPINFOA siStartInfo;
    ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
    ZeroMemory( &siStartInfo, sizeof(STARTUPINFOA) );
    siStartInfo.cb = sizeof(STARTUPINFOA); 
    if (fileIN != "")
    	siStartInfo.hStdInput = hFile;
    else siStartInfo.hStdInput = fdin;

    siStartInfo.hStdOutput = fds[0][1];
    siStartInfo.hStdError = fds[1][1];
    siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
    if (!CreateProcessA(NULL, 
      (char*)newCommand.c_str(),       // command line 
      NULL,          // process security attributes 
      NULL,          // primary thread security attributes 
      TRUE,          // handles are inherited 
      0,             // creation flags 
      NULL,          // use parent's environment 
      NULL,          // use parent's current directory 
      &siStartInfo,  // STARTUPINFO pointer 
      &piProcInfo))  // receives PROCESS_INFORMATION 
    {
		std::cerr << "CreateProcess failed : "<<GetLastError()<<std::endl;
	return 1;
    }

    { // parent process
	//char inbuf[BUFSIZE];
	char buf[2][BUFSIZE];
	int nfill[2];
    CloseHandle(fds[0][1]);
	CloseHandle(fds[1][1]);
	unsigned long exit = 0;
	for (int i=0;i<2;i++)
	    nfill[i] = 0;
	for(int i=0;;i++)
	{
	    GetExitCodeProcess(piProcInfo.hProcess,&exit);      //while the process is running
	    if (exit != STILL_ACTIVE)
		break;
		
	    bool busy = false;
	    for (int i=0;i<2;i++)
	    {
			DWORD n = BUFSIZE-nfill[i];
			if (n > STEPSIZE) n = STEPSIZE;
			DWORD bread = 0;
			DWORD avail = 0;
			PeekNamedPipe(fds[i][0],buf[i]+nfill[i],n,&bread,&avail,NULL);
			
			if (bread>0)
			{
				busy = true;
				ReadFile(fds[i][0], buf[i]+nfill[i], n, &n, NULL);
				nfill[i] += n;
				{
					// write line
		    		if (i==0)
						outStream << std::string(buf[i],nfill[i]);
					else
						errorStream << std::string(buf[i],nfill[i]);

					//std::cout << std::string(buf[i],nfill[i]) << std::endl;
					nfill[i] = 0;
				}
			}
		}
	    if (!busy)
		Sleep(0);
	}
	CloseHandle(fds[0][0]);
	CloseHandle(fds[1][0]);
	int status=exit;
	CloseHandle(piProcInfo.hProcess);
	CloseHandle(piProcInfo.hThread);
	//waitpid(pid,&status,0);
#else
	int filefd = 0;
    if (fileIN != "")
    	filefd = open(fileIN.c_str(),O_RDONLY);
    
    pid_t   pid;
	pid = fork();
	if (pid < 0)
	{
		std::cerr << "fork failed."<<std::endl;
		return false;
	}
	else if (pid == 0)
	{ // child process
		close(fds[0][0]);
		close(fds[1][0]);
		// Remove standard input
		if (fileIN != "")
			dup2(filefd, 0);
		else dup2(open("/dev/null",O_RDONLY),0);
		
		dup2(fds[0][1],1);
		dup2(fds[1][1],2);
		
		int retexec = execvp(command.c_str(), cargs);
		std::cerr << "PipeProcess : ERROR: execlp( "<< command.c_str() << " " ;
		for (unsigned int i=0; i<args.size() + 1 ; i++)
			std::cerr << cargs[i] << " ";
		std::cerr << ") returned "<<retexec<<std::endl;
		return false;
	}
	else
	{ // parent process
//		char inbuf[BUFSIZE];
		char buf[2][BUFSIZE];
		int nfill[2];
		close(fds[0][1]);
		close(fds[1][1]);
		fd_set rfds;
		int nfd = fdin+1;
		FD_ZERO(&rfds);
		FD_SET(fdin, &rfds);
		int nopen = 0;
		for (int i=0;i<2;i++)
		{
			//fcntl(fds[i][0],F_SETFL, fcntl(fds[i][0],F_GETFL)|O_NONBLOCK );
			FD_SET(fds[i][0], &rfds);
			if (fds[i][0] >= nfd) nfd = fds[i][0]+1;
			// add prefixes
			//buf[i][0] = '0'+i;
			//nfill[i] = 1;
			nfill[i] = 0;
			++nopen;
		}
		fd_set ready;
		ready = rfds;
		while (nopen> 0 && select(nfd, &ready, NULL, NULL, NULL)> 0)
		{
			//read stdin
//			if (FD_ISSET(fdin, &ready))
//			{
//				int n = read(fdin, inbuf, BUFSIZE);
//				if (n>0)
//				{
//					writeall(2,inbuf,n);
//				}
//				else if (n==0)
//				{
//					FD_CLR(fdin, &rfds);
//				}
//			}
			for (int i=0;i<2;i++)
			{
				if (FD_ISSET(fds[i][0], &ready))
				{
					int n = BUFSIZE-nfill[i];
					if (n> STEPSIZE) n = STEPSIZE;
					n = read(fds[i][0], buf[i]+nfill[i], n);
					
					if (n == 0)
					{
						if (nfill[i]> 1)
						{
							buf[i][nfill[i]] = '\n';
							if (i==0) 
								outStream << std::string(buf[i],nfill[i]+1);
							else
								errorStream << std::string(buf[i],nfill[i]+1);
						}
						--nopen;
						FD_CLR(fds[i][0], &rfds);	
					}
					else
					{
						nfill[i] += n;
					
						// write line
			    		if (i==0)
							outStream << std::string(buf[i],nfill[i]);
						else
							errorStream << std::string(buf[i],nfill[i]);

						//std::cout << std::string(buf[i],nfill[i]) << std::endl;
						nfill[i] = 0;
					}
					
				}
			}
			ready = rfds;
		}
		close(fds[0][0]);
		close(fds[1][0]);
		int status=0;
		waitpid(pid,&status,0);

		if (fdout != 1)
			close(fdout);
		close(filefd);
#endif
		
		
		outString = outStream.str();
		errorString = errorStream.str();
		return (status == 0);
	}
}

}
}
}