Пример #1
0
void ServPanelist ( Connection panelist, struct sockaddr_in client)
{
    int psd, index=0;
    pid_t childpid;
	int *status;
	
    socklen_t t = sizeof(panelist.server);
	
	signal(SIGPIPE, PIPEhandler);
	
    for(;;){
        psd  = accept(panelist.socket_s, (struct sockaddr *) &client, &t);
        EchoServe(psd, client, GETUSERNAME);
        childpid = fork();
        if ( childpid == 0) {
			signal (SIGQUIT, SIG_IGN);
			signal (SIGINT, SIG_IGN);		
			signal (SIGTSTP,SIG_IGN); 

            if (signal(SIGUSR1, displayHandle) == SIG_ERR) {
                fprintf(stderr, "cannot set handler for SIGUSR1\n");
            }

            if (signal(SIGUSR2, SendMessage) == SIG_ERR) {
                fprintf(stderr, "cannot set handler for SIGUSR2\n");
            }

            close (panelist.socket_s);
            EchoServe(psd, client, SERVPANEL);
        }
        else{
            
			signal (SIGQUIT, SIG_IGN);
			signal (SIGINT, SIG_IGN);		
			signal (SIGTSTP,SIG_IGN); 

            cout << "\nNew Panel Client: (" << inet_ntoa(client.sin_addr) << ":" << ntohs(client.sin_port) <<
                    ") [" << client_msg << "]" << endl;
            cout << "Forked Panel Handler, PID = " << childpid << endl;
			
			*sharedInt_index = *sharedInt_index + 1 ;
			index = *sharedInt_index;
			
			//cout << "new parti " << index <<endl;
			list_participants[index].client_type = PARTICIPANT_PAN;
			list_participants[index].pid = childpid;
			list_participants[index].port = client.sin_port;
			list_participants[index].address = client.sin_addr;
			list_participants[index].buf_stream = psd;
			strcpy(list_participants[index].user_name, client_msg);		
			// current date/time based on current system
			list_participants[index].time_in = time (NULL);		
        }

		//Handle the child signal just end. Meaning of someone left the room. Pipe broken.
		int pid=wait(&status);	
		//#define PARTICIPANT_AUD    	   1
		//#define PARTICIPANT_PAN        2
		//checkParticipant(index,PARTICIPANT_PAN);	
    }
}
Пример #2
0
/*------------------------------------------------------------------------
 * rdsprocess  -  High-priority background process to repeatedly extract
 *		  an item from the request queue and send the request to
 *		  the remote disk server
 *------------------------------------------------------------------------
 */
void	rdsprocess (
	  struct rdscblk    *rdptr	/* Ptr to device control block	*/
	)
{
	struct	rd_msg_wreq msg;	/* Message to be sent		*/
					/*   (includes data area)	*/
	struct	rd_msg_rres resp;	/* Buffer to hold response	*/
					/*   (includes data area)	*/
	int32	retval;			/* Return value from rdscomm	*/
	char	*idto;			/* Ptr to ID string copy	*/
	char	*idfrom;		/* Ptr into ID string		*/
	struct	rdbuff	*bptr;		/* Ptr to buffer at the head of	*/
					/*   the request queue		*/
	struct	rdbuff	*nptr;		/* Ptr to next buffer on the	*/
					/*   request queue		*/
	struct	rdbuff	*pptr;		/* Ptr to previous buffer	*/
	struct	rdbuff	*qptr;		/* Ptr that runs along the	*/
					/*   request queue		*/
	int32	i;			/* Loop index			*/

	while (TRUE) {			/* Do forever */

	    /* Wait until the request queue contains a node */
	    wait(rdptr->rd_reqsem);
	    bptr = rdptr->rd_rhnext;

	    /* Use operation in request to determine action */

	   switch (bptr->rd_op) {

	   case RD_OP_READ:

		/* Build a read request message for the server */

		msg.rd_type = htons(RD_MSG_RREQ);	/* Read request	*/
		msg.rd_blk = htonl(bptr->rd_blknum);
		msg.rd_status = htons(0);
		msg.rd_seq = 0;		/* Rdscomm fills in an entry	*/
		idto = msg.rd_id;
		memset(idto, NULLCH, RD_IDLEN);/* Initialize ID to zero	*/
		idfrom = rdptr->rd_id;
		while ( (*idto++ = *idfrom++) != NULLCH ) { /* Copy ID	*/
			;
		}

		/* Send the message and receive a response */

		retval = rdscomm((struct rd_msg_hdr *)&msg,
					sizeof(struct rd_msg_rreq),
				 (struct rd_msg_hdr *)&resp,
					sizeof(struct rd_msg_rres),
				  rdptr );

		/* Check response */

		if ( (retval == SYSERR) || (retval == TIMEOUT) ||
				(ntohs(resp.rd_status) != 0) ) {
			panic("Failed to contact remote disk server");
		}

		/* Copy data from the reply into the buffer */

		for (i=0; i<RD_BLKSIZ; i++) {
			bptr->rd_block[i] = resp.rd_data[i];
		}

		/* Unlink buffer from the request queue */

		nptr = bptr->rd_next;
		pptr = bptr->rd_prev;
		nptr->rd_prev = bptr->rd_prev;
		pptr->rd_next = bptr->rd_next;

		/* Insert buffer in the cache */

		pptr = (struct rdbuff *) &rdptr->rd_chnext;
		nptr = pptr->rd_next;
		bptr->rd_next = nptr;
		bptr->rd_prev = pptr;
		pptr->rd_next = bptr;
		nptr->rd_prev = bptr;

		/* Initialize reference count */

		bptr->rd_refcnt = 1;

		/* Signal the available semaphore */

		signal(rdptr->rd_availsem);

		/* Send a message to waiting process */

		send(bptr->rd_pid, (uint32)bptr);

		/* If other processes are waiting to read the  */
		/*   block, notify them and remove the request */

		qptr = rdptr->rd_rhnext;
		while (qptr != (struct rdbuff *)&rdptr->rd_rtnext) {
			if (qptr->rd_blknum == bptr->rd_blknum) {
				bptr->rd_refcnt++;
				send(qptr->rd_pid,(uint32)bptr);

				/* Unlink request from queue	*/

				pptr = qptr->rd_prev;
				nptr = qptr->rd_next;
				pptr->rd_next = bptr->rd_next;
				nptr->rd_prev = bptr->rd_prev;

				/* Move buffer to the free list	*/

				qptr->rd_next = rdptr->rd_free;
				rdptr->rd_free = qptr;
				signal(rdptr->rd_availsem);
				break;
			}
			qptr = qptr->rd_next;
		}
		break;

	    case RD_OP_WRITE:

		/* Build a write request message for the server */

		msg.rd_type = htons(RD_MSG_WREQ);	/* Write request*/
		msg.rd_blk = htonl(bptr->rd_blknum);
		msg.rd_status = htons(0);
		msg.rd_seq = 0;		/* Rdscomb fills in an entry	*/
		idto = msg.rd_id;
		memset(idto, NULLCH, RD_IDLEN);/* Initialize ID to zero	*/
		idfrom = rdptr->rd_id;
		while ( (*idto++ = *idfrom++) != NULLCH ) { /* Copy ID	*/
			;
		}
		for (i=0; i<RD_BLKSIZ; i++) {
			msg.rd_data[i] = bptr->rd_block[i];
		}

		/* Unlink buffer from request queue */

		nptr = bptr->rd_next;
		pptr = bptr->rd_prev;
		pptr->rd_next = nptr;
		nptr->rd_prev = pptr;

		/* Insert buffer in the cache */

		pptr = (struct rdbuff *) &rdptr->rd_chnext;
		nptr = pptr->rd_next;
		bptr->rd_next = nptr;
		bptr->rd_prev = pptr;
		pptr->rd_next = bptr;
		nptr->rd_prev = bptr;

		/* Declare that buffer is eligible for reuse */

		bptr->rd_refcnt = 0;
		signal(rdptr->rd_availsem);

		/* Send the message and receive a response */

		retval = rdscomm((struct rd_msg_hdr *)&msg,
					sizeof(struct rd_msg_wreq),
				 (struct rd_msg_hdr *)&resp,
					sizeof(struct rd_msg_wres),
				  rdptr );

		/* Check response */

		if ( (retval == SYSERR) || (retval == TIMEOUT) ||
				(ntohs(resp.rd_status) != 0) ) {
			panic("failed to contact remote disk server");
		}
		break;

	    case RD_OP_SYNC:

		/* Send a message to the waiting process */

		send(bptr->rd_pid, OK);

		/* Unlink buffer from the request queue */

		nptr = bptr->rd_next;
		pptr = bptr->rd_prev;
		nptr->rd_prev = bptr->rd_prev;
		pptr->rd_next = bptr->rd_next;

		/* Insert buffer into the free list */

		bptr->rd_next = rdptr->rd_free;
		rdptr->rd_free = bptr;
		signal(rdptr->rd_availsem);
		break;
	   }
	   sleepms(1);
	}
}
Пример #3
0
int
main(int argc, char **argv)
{
#ifdef WINDOWS
    HANDLE event;
    char cmdline[128];

    if (argc == 1) {
        /* parent process */
        STARTUPINFO si = { sizeof(STARTUPINFO) };
        PROCESS_INFORMATION pi;
        HANDLE job, job2, job3;
        JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit = {0,};
        DWORD exitcode = (DWORD)-1;

        /* For synchronization we create an inherited event */
        SECURITY_ATTRIBUTES sa = {sizeof(sa), NULL, TRUE/*inherit*/};
        event = CreateEvent(&sa, FALSE/*manual reset*/, FALSE/*start unset*/, NULL);
        if (event == NULL)
            print("Failed to create event");

        _snprintf(cmdline, BUFFER_SIZE_ELEMENTS(cmdline), "%s %p", argv[0], event);

        print("creating child #1\n");
        if (!CreateProcess(argv[0], cmdline, NULL, NULL, TRUE/*inherit handles*/,
                           0, NULL, NULL, &si, &pi))
            print("CreateProcess failure\n");
        WaitForSingleObject(event, INFINITE);
        print("terminating child #1 by NtTerminateProcess\n");
        TerminateProcess(pi.hProcess, 42);
        WaitForSingleObject(pi.hProcess, INFINITE);
        GetExitCodeProcess(pi.hProcess, &exitcode);
        print("child #1 exit code = %d\n", exitcode);
        if (!ResetEvent(event))
            print("Failed to reset event\n");

        print("creating child #2\n");
        if (!CreateProcess(argv[0], cmdline, NULL, NULL, TRUE/*inherit handles*/,
                           CREATE_SUSPENDED, NULL, NULL, &si, &pi))
            print("CreateProcess failure\n");
        job = CreateJobObject(NULL, "drx-test job");
        AssignProcessToJobObject(job, pi.hProcess);
        ResumeThread(pi.hThread);
        CloseHandle(pi.hThread);
        WaitForSingleObject(event, INFINITE);
        print("terminating child #2 by NtTerminateJobObject\n");
        TerminateJobObject(job, 123456);
        CloseHandle(job);
        WaitForSingleObject(pi.hProcess, INFINITE);
        GetExitCodeProcess(pi.hProcess, &exitcode);
        print("child #2 exit code = %d\n", exitcode);
        if (!ResetEvent(event))
            print("Failed to reset event\n");

        print("creating child #3\n");
        if (!CreateProcess(argv[0], cmdline, NULL, NULL, TRUE/*inherit handles*/,
                           CREATE_SUSPENDED, NULL, NULL, &si, &pi))
            print("CreateProcess failure\n");
        job = CreateJobObject(NULL, "drx-test job");
        AssignProcessToJobObject(job, pi.hProcess);
        limit.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
        if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation,
                                     &limit, sizeof(limit)))
            print("SetInformationJobObject failed\n");
        ResumeThread(pi.hThread);
        CloseHandle(pi.hThread);
        WaitForSingleObject(event, INFINITE);
        print("terminating child #3 by closing job handle\n");
        CloseHandle(job);
        WaitForSingleObject(pi.hProcess, INFINITE);
        GetExitCodeProcess(pi.hProcess, &exitcode);
        print("child #3 exit code = %d\n", exitcode);

        /* Test DuplicateHandle (DrMem i#1401) */
        print("creating child #4\n");
        if (!CreateProcess(argv[0], cmdline, NULL, NULL, TRUE/*inherit handles*/,
                           CREATE_SUSPENDED, NULL, NULL, &si, &pi))
            print("CreateProcess failure\n");
        job = CreateJobObject(NULL, "drx-test job");
        AssignProcessToJobObject(job, pi.hProcess);
        limit.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
        if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation,
                                     &limit, sizeof(limit)))
            print("SetInformationJobObject failed\n");
        if (!DuplicateHandle(GetCurrentProcess(), job, GetCurrentProcess(), &job2,
                             0, FALSE, DUPLICATE_SAME_ACCESS))
            print("DuplicateHandle failed\n");
        if (!DuplicateHandle(GetCurrentProcess(), job, GetCurrentProcess(), &job3,
                             0, FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
            print("DuplicateHandle failed\n");
        ResumeThread(pi.hThread);
        CloseHandle(pi.hThread);
        WaitForSingleObject(event, INFINITE);
        print("terminating child #4 by closing both job handles\n");
        CloseHandle(job2);
        CloseHandle(job3);
        WaitForSingleObject(pi.hProcess, INFINITE);
        GetExitCodeProcess(pi.hProcess, &exitcode);
        print("child #4 exit code = %d\n", exitcode);
    }
    else { /* child process */
        int iter = 0;
        if (sscanf(argv[1], "%p", &event) != 1) {
            print("Failed to obtain event handle from %s\n", argv[1]);
            return -1;
        }
        if (!SetEvent(event))
            print("Failed to set event\n");
        /* spin until parent kills us or we time out */
        while (iter++ < 12) {
            Sleep(5000);
        }
    }

    CloseHandle(event);

#else /* WINDOWS */

    int pipefd[2];
    pid_t cpid;
    char buf = 0;

    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(1);
    }

    print("creating child\n");
    cpid = fork();
    if (cpid == -1) {
        perror("fork");
        exit(1);
    } else if (cpid > 0) {
        /* parent */
        int status;
        close(pipefd[1]); /* close unused write end */
        if (read(pipefd[0], &buf, sizeof(buf)) <= 0) {
            perror("pipe read failed");
            exit(1);
        }
        print("terminating child by sending SIGKILL\n");
        kill(cpid, SIGKILL);
        wait(&status); /* wait for child */
        close(pipefd[0]);
        print("child exit code = %d\n", status);
    } else {
        /* child */
        int iter = 0;
        close(pipefd[0]); /* close unused read end */
        write(pipefd[1], &buf, sizeof(buf));
        close(pipefd[1]);
        /* spin until parent kills us or we time out */
        while (iter++ < 12) {
            sleep(5);
        }
    }

#endif /* UNIX */

    return 0;
}
Пример #4
0
bool SynchronizableMulti::wait(int id, int q, bool front, long seconds) {
    return wait(id, q, front, seconds, 0);
}
Пример #5
0
void obtain_measurement()
{
	AnalogIn       temperature_sensor(p15);
	uint16_t       sensor_value;			// value read from the analog in
	float          temperature;				// to store the value after the conversion from mV
	float          voltage;					// conversion from integer to mV
	char		   float_converted[50];				// to store the result of the conversion


	myled = 1;					// turn on, something to transmit


	sensor_value = temperature_sensor.read_u16();
	voltage = (sensor_value / 65536.0 ) * 3.3;
	temperature = (voltage - .5) * 100;


	sprintf(float_converted, "%f", temperature);

	rn42.putc('*');
	wait(0.1);
	rn42.putc(' ');
	wait(0.1);
	rn42.putc('2');
	wait(0.1);
	rn42.putc(' ');
	wait(0.1);
	rn42.putc(float_converted[0]);
	wait(0.1);
	rn42.putc(float_converted[1]);
	wait(0.1);
	rn42.putc(float_converted[2]);
	wait(0.1);
	rn42.putc(float_converted[3]);
	wait(0.1);
	rn42.putc(float_converted[4]);
	wait(0.1);
	rn42.putc(' ');
	wait(0.1);
	rn42.putc('#');
	wait(0.1);
	rn42.putc('#');
	wait(0.1);
	rn42.putc('#');
	wait(0.1);
	rn42.putc('#');
	wait(0.1);
	rn42.putc('#');
	wait(0.1);
	rn42.putc(' ');
	wait(0.1);
	rn42.putc('*');

	myled = 0;
}
Пример #6
0
/*
 *收到SIGCHLD信号之后的回调函数
 */
static void wait_child(int sig_type)
{
	int status;
	pid_t pid = wait(&status);
	del_from_PL(pid);
}
Пример #7
0
Файл: 2-1.c Проект: jiezh/h5vcc
int main()
{

    /* Make sure there is process-shared capability. */
#ifndef PTHREAD_PROCESS_SHARED
    fprintf(stderr,"process-shared attribute is not available for testing\n");
    return PTS_UNSUPPORTED;
#endif

    static pthread_barrier_t* barrier;
    pthread_barrierattr_t ba;
    int	pshared = PTHREAD_PROCESS_SHARED;

    char 	shm_name[] = "tmp_pthread_barrierattr_getpshared";
    int 	shm_fd;
    int 	pid;
    int 	loop;
    int	serial = 0;
    int	rc;
    int	status = 0;
    struct sigaction act;

    /* Set up parent to handle SIGALRM */
    act.sa_flags = 0;
    act.sa_handler = sig_handler;
    sigfillset(&act.sa_mask);
    sigaction(SIGALRM, &act, 0);

    /* Initialize a barrier attributes object */
    if(pthread_barrierattr_init(&ba) != 0)
    {
        printf("Error at pthread_barrierattr_init()\n");
        return PTS_UNRESOLVED;
    }

    /* Set the pshard value to private to shared */
    if(pthread_barrierattr_setpshared(&ba, pshared) != 0)
    {
        printf("Error at pthread_barrierattr_setpshared()\n");
        return PTS_UNRESOLVED;
    }

    if(pthread_barrierattr_getpshared(&ba, &pshared) != 0)
    {
        printf("Test FAILED: Error at pthread_barrierattr_getpshared()\n");
        return PTS_FAIL;
    }

    if(pshared != PTHREAD_PROCESS_SHARED)
    {
        printf("Test FAILED: Incorrect pshared value %d\n", pshared);
        return PTS_FAIL;
    }

    /* Create shared object */
    shm_unlink(shm_name);
    shm_fd = shm_open(shm_name, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR);
    if(shm_fd == -1)
    {
        perror("Error at shm_open()");
        return PTS_UNRESOLVED;
    }

    if(ftruncate(shm_fd, sizeof(pthread_barrier_t)) != 0)
    {
        perror("Error at ftruncate()");
        shm_unlink(shm_name);
        return PTS_UNRESOLVED;
    }

    /* Map the shared memory object to my memory */
    barrier = mmap(NULL, sizeof(pthread_barrier_t), PROT_READ|PROT_WRITE,
                   MAP_SHARED, shm_fd, 0);

    if(barrier == MAP_FAILED)
    {
        perror("Error at first mmap()");
        shm_unlink(shm_name);
        return PTS_UNRESOLVED;
    }

    /* Initialize a barrier */
    if((pthread_barrier_init(barrier, &ba, 2)) != 0)
    {
        printf("Error at pthread_barrier_init()\n");
        return PTS_UNRESOLVED;
    }

    /* Cleanup */
    if((pthread_barrierattr_destroy(&ba)) != 0)
    {
        printf("Error at pthread_barrierattr_destroy()\n");
        return PTS_UNRESOLVED;
    }

    /* Fork a child process */
    pid = fork();
    if(pid == -1)
    {
        perror("Error at fork()");
        return PTS_UNRESOLVED;
    }
    else if(pid == 0)
    {
        /* Child */
        /* Map the shared object to child's memory */
        barrier = mmap(NULL, sizeof(pthread_barrier_t), PROT_READ|PROT_WRITE,
                       MAP_SHARED, shm_fd, 0);

        if(barrier == MAP_FAILED)
        {
            perror("child: Error at first mmap()");
            return PTS_UNRESOLVED;
        }
    }
    else
    {
        printf("parent pid : %d, child pid : %d\n", getpid(), pid);
        printf("parent: send me SIGALRM 2 secs later in case I am blocked\n");
        alarm(2);
    }

    for(loop = 0; loop < LOOP_NUM; loop++)
    {
        rc = pthread_barrier_wait(barrier);
        if(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
        {
            printf("Test FAILED: %d: pthread_barrier_wait() got unexpected "
                   "return code : %d\n" , getpid(), rc);
            exit(PTS_FAIL);
        }
        else if(rc == PTHREAD_BARRIER_SERIAL_THREAD)
        {
            serial++;
            printf("process %d: get PTHREAD_BARRIER_SERIAL_THREAD\n"
                   , getpid());
        }

    }

    if(pid > 0)
    {
        /* parent */
        if( wait(&status) != pid)
        {
            printf("parent: error at waitpid()\n");
            return PTS_UNRESOLVED;
        }

        if(!WIFEXITED(status))
        {
            printf("Child exited abnormally\n");
            return PTS_UNRESOLVED;
        }

        if((WEXITSTATUS(status) + serial) != LOOP_NUM)
        {
            printf("status = %d\n", status);
            printf("serial = %d\n", serial);
            printf("Test FAILED: One of the two processes should get "
                   "PTHREAD_BARRIER_SERIAL_THREAD\n");
            return PTS_FAIL;
        }

        /* Cleanup */
        if(pthread_barrier_destroy(barrier) != 0)
        {
            printf("Error at pthread_barrier_destroy()");
            return PTS_UNRESOLVED;
        }

        if((shm_unlink(shm_name)) != 0)
        {
            perror("Error at shm_unlink()");
            return PTS_UNRESOLVED;
        }

        printf("Test PASSED\n");
        return PTS_PASS;
    }

    if(pid == 0)
    {
        exit(serial);
    }

    return PTS_UNRESOLVED;
}
 int wait_and_end(int i)
 {
   wait( i + 1, SC_NS);
   cout << "Thread " << i << " ending." << endl;
   return 0;
 }
Пример #9
0
void wait(F&& ...f)
{
    using swallow = int[];
    (void)swallow{(wait(std::forward<F>(f)), 0)...};
}
Пример #10
0
/*---------------------------------------------------------------------+
|                                 main                                 |
| ==================================================================== |
|                                                                      |
| Function:  ...                                                       |
|                                                                      |
+---------------------------------------------------------------------*/
int main(int argc, char **argv)
{
	char *filename = NULL;
	FILE *statfile;
	pid_t pid = 0;
	int fd;
	int rc;
	clock_t start_time;	/* start & stop times */
	clock_t stop_time;
	float elapsed_time;
#ifdef __linux__
	time_t timer_info;
#else
	struct tms timer_info;	/* time accounting info */
#endif

	if ((filename = getenv("KERNEL")) == NULL) {
		errno = ENODATA;
		sys_error("environment variable KERNEL not set", __FILE__,
			  __LINE__);
	}

	/* Process command line arguments...  */
	parse_args(argc, argv);
	if (verbose)
		printf("%s: Scheduler TestSuite program\n\n", *argv);
	if (debug) {
		printf("\tpriority type:  %s\n", priority_type);
		printf("\tpriority:       %d\n", priority);
		printf("\tlogfile:        %s\n", logfile);
	}

	/* Adjust the priority of this process if the real time flag is set */
	if (!strcmp(priority_type, "fixed")) {
#ifndef __linux__
		if (setpri(0, DEFAULT_PRIORITY) < 0)
			sys_error("setpri failed", __FILE__, __LINE__);
#else
		if (setpriority(PRIO_PROCESS, 0, 0) < 0)
			sys_error("setpri failed", __FILE__, __LINE__);
#endif
	} else {
		if (nice((priority - 50) - (nice(0) + 20)) < 0 && errno != 0)
			sys_error("nice failed", __FILE__, __LINE__);
	}

	/* Read from raw I/O device and record elapsed time...  */
	start_time = time(&timer_info);

	/* Open and lock file file...  */
	fd = open_file(filename, O_RDWR);
	if (!lock_file(fd, F_WRLCK, filename))	/* set exclusive lock */
		error("lock_file failed", __FILE__, __LINE__);

	/* If fork flag set, fork a real process */
	if (fork_flag)
		pid = fork_realtime(argv);

	/* Read file */
	if (debug) {
		printf("\tprocess id %d successfully locked %s\n",
		       getpid(), filename);
		printf("\tprocess id %d starting to read %s\n",
		       getpid(), filename);
	}

	if (!read_file(fd, filename))
		error("read_file failed", __FILE__, __LINE__);

	/* Stop the timer and calculate the elapsed time */
	stop_time = time(&timer_info);
	elapsed_time = (float)(stop_time - start_time) / 100.0;

	/* Write the elapsed time to the temporary file...  */
	if ((statfile = fopen(logfile, "w")) == NULL)
		sys_error("fopen failed", __FILE__, __LINE__);

	fprintf(statfile, "%f\n", elapsed_time);
	if (debug)
		printf("\n\telapsed time: %f\n", elapsed_time);

	if (fclose(statfile) < 0)
		sys_error("fclose failed", __FILE__, __LINE__);

	/* Unlock file at latest possible time to prevent real time child from
	 * writing throughput results before user process parent */
	unlock_file(fd, filename);
	close(fd);

	if (debug)
		printf("\tprocess id %d completed read and unlocked file\n",
		       getpid());

	/* The parent waits for child process to complete before exiting
	 * so the driver will not read the throughput results file before
	 * child writes to the file */
	if (pid != 0) {		/* if parent process ... *//* wait for child process */
		if (debug)
			printf
			    ("parent waiting on child process %d to complete\n",
			     pid);

		while ((rc = wait(NULL)) != pid)
			if (rc == -1)
				sys_error("wait failed", __FILE__, __LINE__);
/*
DARA: which one to use
1st -- hangs
2nd -- ERROR message

	    while (wait((void *) 0) != pid) ;
	    while ((rc=wait ((void *) 0)) != pid)
	       if (rc == -1)
	          sys_error ("wait failed", __FILE__, __LINE__);
*/
	}

	/* Exit with success! */
	if (verbose)
		printf("\nsuccessful!\n");
	return (0);
}
Пример #11
0
static void
vfstest_s5fs_vm(void)
{
        int fd, newfd, ret;
        char buf[2048];
        struct stat oldstatbuf, newstatbuf;
        void *addr;

        syscall_success(mkdir("s5fs", 0));
        syscall_success(chdir("s5fs"));

        /* Open some stuff */
        syscall_success(fd = open("oldchld", O_RDWR | O_CREAT, 0));
        syscall_success(mkdir("parent", 0));

        /* link/unlink tests */
        syscall_success(link("oldchld", "newchld"));

        /* Make sure stats match */
        syscall_success(stat("oldchld", &oldstatbuf));
        syscall_success(stat("newchld", &newstatbuf));
        test_assert(0 == memcmp(&oldstatbuf, &newstatbuf, sizeof(struct stat)), NULL);

        /* Make sure contents match */
        syscall_success(newfd = open("newchld", O_RDWR, 0));
        syscall_success(ret = write(fd, TESTSTR, strlen(TESTSTR)));
        test_assert(ret == (int)strlen(TESTSTR), NULL);
        syscall_success(ret = read(newfd, buf, strlen(TESTSTR)));
        test_assert(ret == (int)strlen(TESTSTR), NULL);
        test_assert(0 == strncmp(buf, TESTSTR, strlen(TESTSTR)), "string is %.*s, expected %s", strlen(TESTSTR), buf, TESTSTR);

        syscall_success(close(fd));
        syscall_success(close(newfd));

        /* Remove one, make sure the other remains */
        syscall_success(unlink("oldchld"));
        syscall_fail(mkdir("newchld", 0), EEXIST);
        syscall_success(link("newchld", "oldchld"));

        /* Link/unlink error cases */
        syscall_fail(link("oldchld", "newchld"), EEXIST);
        syscall_fail(link("oldchld", LONGNAME), ENAMETOOLONG);
        syscall_fail(link("parent", "newchld"), EISDIR);

        /* only rename test */
        /*syscall_success(rename("oldchld", "newchld"));*/

        /* mmap/munmap tests */
        syscall_success(fd = open("newchld", O_RDWR, 0));
        test_assert(MAP_FAILED != (addr = mmap(0, strlen(TESTSTR), PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)), NULL);
        /* Check contents of memory */
        test_assert(0 == memcmp(addr, TESTSTR, strlen(TESTSTR)), NULL);

        /* Write to it -> we shouldn't pagefault */
        memcpy(addr, SHORTSTR, strlen(SHORTSTR));
        test_assert(0 == memcmp(addr, SHORTSTR, strlen(SHORTSTR)), NULL);

        /* mmap the same thing on top of it, but shared */
        test_assert(MAP_FAILED != mmap(addr, strlen(TESTSTR), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0), NULL);
        /* Make sure the old contents were restored (the mapping was private) */
        test_assert(0 == memcmp(addr, TESTSTR, strlen(TESTSTR)), NULL);

        /* Now change the contents */
        memcpy(addr, SHORTSTR, strlen(SHORTSTR));
        /* mmap it on, private, on top again */
        test_assert(MAP_FAILED != mmap(addr, strlen(TESTSTR), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED, fd, 0), NULL);
        /* Make sure it changed */
        test_assert(0 == memcmp(addr, SHORTSTR, strlen(SHORTSTR)), NULL);

        /* Fork and try changing things */
        if (!fork()) {
                /* Child changes private mapping */
                memcpy(addr, TESTSTR, strlen(TESTSTR));
                exit(0);
        }

        /* Wait until child is done */
        syscall_success(wait(0));

        /* Make sure it's actually private */
        test_assert(0 == memcmp(addr, SHORTSTR, strlen(SHORTSTR)), NULL);

        /* Unmap it */
        syscall_success(munmap(addr, 2048));

        /* mmap errors */
        test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, MAP_PRIVATE, 12, 0), NULL);
        test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, MAP_PRIVATE, -1, 0), NULL);
        test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, 0, fd, 0), NULL);
        test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, MAP_FIXED, fd, 0), NULL);
        test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, MAP_FIXED | MAP_PRIVATE, fd, 0), NULL);
        test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, MAP_PRIVATE, fd, 0x12345), NULL);
        test_assert(MAP_FAILED == mmap((void *) 0x12345, 1024, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0), NULL);
        test_assert(MAP_FAILED == mmap(0, 0, PROT_READ, MAP_PRIVATE, fd, 0), NULL);
        test_assert(MAP_FAILED == mmap(0, -1, PROT_READ, MAP_PRIVATE, fd, 0), NULL);
        test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0), NULL);
        syscall_success(close(fd));

        syscall_success(fd = open("newchld", O_RDONLY, 0));
        test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0), NULL);
        syscall_success(close(fd));

        /* TODO ENODEV (mmap a terminal)
           EOVERFLOW (mmap SO MUCH of /dev/zero that fpointer would overflow) */

        /* Also should test opening too many file descriptors somewhere */

        /* munmap errors */
        syscall_fail(munmap((void *) 0x12345, 15), EINVAL);
        syscall_fail(munmap(0x0, 15), EINVAL);
        syscall_fail(munmap(addr, 0), EINVAL);
        syscall_fail(munmap(addr, -1), EINVAL);

        /* brk tests */
        /* Set the break, and use the memory in question */
        test_assert((void *) - 1 != (addr = sbrk(128)), NULL);
        memcpy(addr, TESTSTR, 128);
        test_assert(0 == memcmp(addr, TESTSTR, 128), NULL);

        /* Make sure that the brk is being saved properly */
        test_assert((void *)((unsigned long) addr + 128) == sbrk(0), NULL);
        /* Knock the break back down */
        syscall_success(brk(addr));

        /* brk errors */
        syscall_fail(brk((void *)(&"brk")), ENOMEM);
        syscall_fail(brk((void *) 1), ENOMEM);
        syscall_fail(brk((void *) &addr), ENOMEM);

        syscall_success(chdir(".."));
}
Пример #12
0
 void application::wait_until_quit()
 { try {
     auto wait_ptr_copy = my->_quit_promise; 
     wait_ptr_copy->wait();
 } FC_RETHROW_EXCEPTIONS( warn, "" ) }
Пример #13
0
int main(int argc, char* argv[])
{
    struct sockaddr_in client;

	//Validate input
    if (argc != 2)
    {
        cout << "Usage: panserver <portnumber>" << endl;
        return -1;
    }	
	// initialize shared memory
	initSharedMem();
    // Initialize the ports
    panel.server.sin_port = htons(atoi(argv[1]));
    audience.server.sin_port = htons(atoi(argv[1])+1);

    /** Create socket on which to send  and receive */

    if ( panel.CreatSocket() < 0 ) // create panel socket
        return -1;

    if ( audience.CreatSocket() < 0 ) // create panel socket
        return -1;
	
    reusePort(panel.socket_s); //reuse the binding port when execute program
    
	if ( panel.BindConnection() < 0 ) // Check for binding errors
        return -1;
    
	reusePort(audience.socket_s);//reuse the binding port when execute program
	
    if ( audience.BindConnection() < 0 ) // Check for binding errors
        return -1;

    /** get panel port information and prints it out */
    if ( panel.GetSocketName() ) // check socket name validity
        return -1;

    /** get audience port information and prints it out */
    if ( audience.GetSocketName() ) // check socket name validity
        return -1;
	
    /** accept TCP connections from clients and fork a process to serve each */
    listen(panel.socket_s,10);
    listen(audience.socket_s,10);
	
	signal(SIGPIPE, PIPEhandler);
	
	
	for(;;){
        audience_pid = fork();
		signal (SIGINT, SIG_IGN);
		signal (SIGTSTP,SIG_IGN); 
        
        /* This is the audience server */
        if ( audience_pid == 0) {
		        cout << "Forked AUDIENCE Server, PID=" << getpid() << endl;
				
				ServPanelist(panel, client);
        }
        else
        {
			panel_pid = fork ();
			signal (SIGINT, SIG_IGN);
			signal (SIGTSTP,SIG_IGN); 
			//signal(SIGPIPE, PIPEhandler);
			
			if ( panel_pid == 0) {
			    cout << "Forked PANEL Server, PID=" << getpid() << endl;
				ServAudience(audience, client);
			}	
			else
			{
				//list people in the room
				
				cout << "AUDIENCE server started at port: (" << ntohs(audience.server.sin_port) << ")" << endl;
				cout << "PANELIST server started at port: (" << ntohs(panel.server.sin_port) << ")" << endl;  
				
					
			}
			wait(NULL); 
        }
	   sleep(2);
       wait(NULL); 
    }
}
Пример #14
0
void ServAudience ( Connection audience, struct sockaddr_in client)
{
    int psd, childpid, index=0;
    socklen_t t = sizeof(audience.server);
	int *status;
	
    for(;;){
		psd  = accept(audience.socket_s, (struct sockaddr *) &client, &t);
        EchoServe(psd, client, GETUSERNAME);
        childpid = fork();
        if ( childpid == 0) {
			signal (SIGTSTP,SIG_IGN);
			if (signal(SIGUSR1, displayHandle) == SIG_ERR) {
                fprintf(stderr, "cannot set handler for SIGUSR1\n");
            }
            
			// getting interrupt to send an audience message
            if (signal(SIGUSR2, SendMessage) == SIG_ERR) {
                fprintf(stderr, "cannot set handler for SIGUSR2\n");
            }
            
			close (audience.socket_s);
            EchoServe(psd, client, SERVAUDIENCE);
			
        }
        else{
			signal (SIGTSTP,SIG_IGN);
			cout << "\nNew audience Client: (" << inet_ntoa(client.sin_addr) << ":" << ntohs(client.sin_port) <<
                    ") [" << client_msg << "]" << endl;
            cout << "Forked audience Handler, PID = " << childpid << endl;
			*sharedInt_index = *sharedInt_index + 1 ;
				index = *sharedInt_index;
				
				//cout << "new parti " << index <<endl;
				list_participants[index].client_type = PARTICIPANT_AUD;
				list_participants[index].pid = childpid;
				list_participants[index].port = client.sin_port;
				list_participants[index].address = client.sin_addr;
				list_participants[index].buf_stream = psd;
				strcpy(list_participants[index].user_name, client_msg);		
				// current date/time based on current system
				list_participants[index].time_in = time (NULL);	
				
				//if Q&A session opened send a message
				if (*QAsessionFlag == 1)
				{
					cout << "We are in Q&A session now!" << endl;
					sprintf(client_msg,"%s", "We are in Q&A session now!");
						if ( send(list_participants[index].buf_stream, client_msg, strlen(client_msg), 0) < 0)
							 
								perror("Error when sending message Q&A to client ");
						 
				}
        }
	
		//Handle the child signal just end. Meaning of someone left the room. Pipe broken.
		int pid=wait(&status);	
		//#define PARTICIPANT_AUD    	   1
		//#define PARTICIPANT_PAN        2
		//checkParticipant(index,PARTICIPANT_AUD);
	 
    }
}
Пример #15
0
void HariMain(void)
{
	int win, timer, i, j, fx, laserwait, lx = 0, ly;
	int ix, iy, movewait0, movewait, idir;
	int invline, score, high, point;
	char winbuf[336 * 261 * osak_getbuflen()], invstr[32 * 6], s[12], keyflag[4], *p;
	static char invstr0[32] = " abcd abcd abcd abcd abcd ";

	win = api_openwin(winbuf, 336, 261, -1, "invader");
	api_boxfilwin(win, 6, 27, 329, 254, 0);
	timer = api_alloctimer();
	api_inittimer(timer, 128);

	high = 0;
	putstr(win, winbuf, 22, 0, 7, "HIGH:00000000");

restart:
	score = 0;
	point = 1;
	putstr(win, winbuf,  4, 0, 7, "SCORE:00000000");
	movewait0 = 20;
	fx = 18;
	putstr(win, winbuf, fx, 13, 6, "efg");
	wait(100, timer, keyflag);

next_group:
	wait(100, timer, keyflag);
	ix = 7;
	iy = 1;
	invline = 6;
	for (i = 0; i < 6; i++) {
		for (j = 0; j < 27; j++) {
			invstr[i * 32 + j] = invstr0[j];
		}
		putstr(win, winbuf, ix, iy + i, 2, invstr + i * 32);
	}
	keyflag[0] = 0;
	keyflag[1] = 0;
	keyflag[2] = 0;

	ly = 0; /* 非表示 */
	laserwait = 0;
	movewait = movewait0;
	idir = +1;
	wait(100, timer, keyflag);

	for (;;) {
		if (laserwait != 0) {
			laserwait--;
			keyflag[2 /* space */] = 0;
		}

		wait(4, timer, keyflag);

		/* 自機の処理 */
		if (keyflag[0 /* left */]  != 0 && fx > 0) {
			fx--;
			putstr(win, winbuf, fx, 13, 6, "efg ");
			keyflag[0 /* left */]  = 0;
		}
		if (keyflag[1 /* right */] != 0 && fx < 37) {
			putstr(win, winbuf, fx, 13, 6, " efg");
			fx++;
			keyflag[1 /* right */] = 0;
		}
		if (keyflag[2 /* space */] != 0 && laserwait == 0) {
			laserwait = 15;
			lx = fx + 1;
			ly = 13;
		}

		/* インベーダ移動 */
		if (movewait != 0) {
			movewait--;
		} else {
			movewait = movewait0;
			if (ix + idir > 14 || ix + idir < 0) {
				if (iy + invline == 13) {
					break; /* GAME OVER */
				}
				idir = - idir;
				putstr(win, winbuf, ix + 1, iy, 0, "                         ");
				iy++;
			} else {
				ix += idir;
			}
			for (i = 0; i < invline; i++) {
				putstr(win, winbuf, ix, iy + i, 2, invstr + i * 32);
			}
		}

		/* レーザー処理 */
		if (ly > 0) {
			if (ly < 13) {
				if (ix < lx && lx < ix + 25 && iy <= ly && ly < iy + invline) {
					putstr(win, winbuf, ix, ly, 2, invstr + (ly - iy) * 32);
				} else {
					putstr(win, winbuf, lx, ly, 0, " ");
				}
			}
			ly--;
			if (ly > 0) {
				putstr(win, winbuf, lx, ly, 3, "h");
			} else {
				point -= 10;
				if (point <= 0) {
					point = 1;
				}
			}
			if (ix < lx && lx < ix + 25 && iy <= ly && ly < iy + invline) {
				p = invstr + (ly - iy) * 32 + (lx - ix);
				if (*p != ' ') {
					/* hit ! */
					score += point;
					point++;
				//	sprintf(s, "%08d", score);
					setdec8(s, score);
					putstr(win, winbuf, 10, 0, 7, s);
					if (high < score) {
						high = score;
						putstr(win, winbuf, 27, 0, 7, s);
					}
					for (p--; *p != ' '; p--) { }
					for (i = 1; i < 5; i++) {
						p[i] = ' ';
					}
					putstr(win, winbuf, ix, ly, 2, invstr + (ly - iy) * 32);
					for (; invline > 0; invline--) {
						for (p = invstr + (invline - 1) * 32; *p != 0; p++) {
							if (*p != ' ') {
								goto alive;
							}
						}
					}
					/* 全部やっつけられた */
					movewait0 -= movewait0 / 3;
					goto next_group;
	alive:
					ly = 0;
				}
			}
		}
	}

	/* GAME OVER */
	putstr(win, winbuf, 15, 6, 1, "GAME OVER");
	wait(0, timer, keyflag);
	for (i = 1; i < 14; i++) {
		putstr(win, winbuf, 0, i, 0, "                                        ");
	}
	goto restart;
}
Пример #16
0
int main(int ac, char **av)
{
	char iter[20];
	int count, i, nchild, status;
	pid_t pid;

	int lc;
	char *msg;

	if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL)
		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);

	setup();

	if (ac != 5)
		usage();

	for (lc = 0; TEST_LOOPING(lc); lc++) {

		Tst_count = 0;

		prog = av[0];
		iterations = atoi(av[1]);
		fname1 = av[2];
		fname2 = av[3];
		count = atoi(av[4]);
#ifdef DEBUG
		tst_resm(TINFO, "Entered %s %d %s %s %d -- pid = %d", prog,
			 iterations, fname1, fname2, count, getpid());
#endif

		if (iterations == 0) {
			tst_resm(TPASS, "Test DONE, pid %d, -- %s %d %s %s",
				 getpid(), prog, iterations, fname1, fname2);
			tst_exit();
		}

		if (!count) {
			sprintf(iter, "%d", iterations - 1);
			av[0] = fname1;
			av[1] = iter;
			av[2] = fname1;
			av[3] = fname2;
			av[4] = "0";
			av[5] = 0;
			ev[0] = 0;
#ifdef DEBUG
			tst_resm(TINFO, "doing execve(%s, av, ev)", fname1);
			tst_resm(TINFO, "av[0,1,2,3,4] = %s, %s, %s, %s, %s",
				 av[0], av[1], av[2], av[3], av[4]);
#endif
			(void)execve(fname1, av, ev);
			tst_resm(TFAIL, "Execve fail, %s, errno=%d", fname1,
				 errno);
		}

		nchild = count * 2;

		sprintf(iter, "%d", iterations);
		for (i = 0; i < count; i++) {

			pid = FORK_OR_VFORK();
			if (pid == -1) {
				perror("fork failed");
				exit(1);
			} else if (pid == 0) {
				av[0] = fname1;
				av[1] = iter;
				av[2] = fname1;
				av[3] = fname2;
				av[4] = "0";
				av[5] = 0;
				ev[0] = 0;
				(void)execve(fname1, av, ev);
				perror("execve failed");
				exit(2);
			}
#ifdef DEBUG
			tst_resm(TINFO, "Main - started pid %d", pid);
#endif
			if (wait(&status) == -1)
				tst_brkm(TBROK|TERRNO, cleanup, "wait failed");
			if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
				tst_resm(TFAIL, "child exited abnormally");

			pid = FORK_OR_VFORK();
			if (pid == -1) {
				perror("Fork failed");
				exit(1);
			} else if (pid == 0) {
				av[0] = fname2;
				av[1] = iter;
				av[2] = fname2;
				av[3] = fname1;
				av[4] = "0";
				av[5] = 0;
				ev[0] = 0;
				execve(fname2, av, ev);
				perror("execve failed");
				exit(2);
			}
#ifdef DEBUG
			tst_resm(TINFO, "Main - started pid %d", pid);
#endif
			if (wait(&status) == -1)
				tst_brkm(TBROK|TERRNO, cleanup, "wait failed");
			if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
				tst_resm(TFAIL, "child exited abnormally");

		}

		if (wait(&status) != -1)
			tst_brkm(TBROK, cleanup,
			    "leftover children haven't exited yet");

	}
	cleanup();

	tst_exit();
}
Пример #17
0
int
main(int argc, char **argv)
{
	char buf[100];
	int i, pid, p[2];


	int fd;
	fd = open("/dev/tty",O_RDWR,0);

	if ((i = pipe(p,0)) < 0)
		panic("pipe: %e", i);

	if ((pid = fork()) < 0)
		panic("fork: %e", i);

	if (pid == 0) {
		printf("[%08x] pipereadeof close %d\n", getpid(), p[1]);
		close(p[1]);
		printf("[%08x] pipereadeof readn %d\n", getpid(), p[0]);
		i = readn(p[0], buf, sizeof buf-1);
		if (i < 0)
			panic("read: %e", i);
		buf[i] = 0;
		if (strcmp(buf, msg) == 0)
			printf("\npipe read closed properly\n");
		else
			printf("\ngot %d bytes: %s\n", i, buf);
		exit();
	} else {
		printf("[%08x] pipereadeof close %d\n", getpid(), p[0]);
		close(p[0]);
		printf("[%08x] pipereadeof write %d\n", getpid(), p[1]);
		if ((i = write(p[1], msg, strlen(msg))) != strlen(msg))
			panic("write: %e", i);
		close(p[1]);
	}
	wait(pid);

	if ((i = pipe(p,0)) < 0)
		panic("pipe: %e", i);

	if ((pid = fork()) < 0)
		panic("fork: %e", i);

	if (pid == 0) {
		close(p[0]);int r = 0;
		while (1) {
			if ((write(p[1], "x", 1)) != 1) {
				break;
			}		
		}	
		printf("\npipe write closed properly\n");
		exit();
	}
	close(p[0]);
	close(p[1]);
	wait(pid);

	printf("pipe tests passed\n");
	return 0;
}
Пример #18
0
rpc_result_object rpc_mclient::call(const std::string& m, const A0& a0) {
  call_(m, msgpack::type::tuple<const A0&>(a0));
  return wait(m);
}
void shmem_int4_wait_f(ompi_fortran_integer4_t *var, ompi_fortran_integer4_t *value)
{
    MCA_SPML_CALL(wait((void*)var, SHMEM_CMP_NE, (void*)value, SHMEM_FINT4));
}
Пример #20
0
void RGBDGrabber :: stop()
{
    setShouldExit();
    newEvent();
    wait();
}
Пример #21
0
int main(int argc, char **argv, char *envp[])
{
    FILE *fp;
    int i=0;
    int p1, p2;
    int status;
    pid_t pid;
    char *envstring, **eval;
    
	/*strncpy(this_file, __FILE__, (strlen(__FILE__) - 2));
	this_file[(strlen(__FILE__) - 2)] = '\0';
	strcat(this_file, ".cgi"); */
    
    strcpy(this_file, "trial_chisq.cgi");

    if (USE_CGI) {
        xcgi_init(argc, argv);
        xcgi_header("html");
    }
    
    p1 = atoi(xcgi_param_value_named("p1"));
    p2 = atoi(xcgi_param_value_named("p2"));
    
    printf( "<html>\n<head>\n<title>trial chisq</title>\n"
            "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"
            "<meta http-equiv=\"expires\" content=\"now\">\n"
			"<meta http-equiv=\"pragma\" content=\"no-cache\">\n"
            "<style type=\"text/css\">\n"
            "<!--\n"
			" body, h1, h2, h3, h4, h5, h6 { font-family: Verdana, sans-serif;}\n"
            " body { font-size: 80%%; }\n"
			" tr.colheader { font-weight: bold; width: 0%% }\n"
			" td { font-size: 80%%; vertical-align: top}\n"
		//	" div.small { font-size: 80%%; }\n"
			" .nowrap {white-space: nowrap}\n"
			"-->\n"
			"</style>\n"
            "</head>\n");
    
    printf("<body bgcolor=\"#fffff0\">\n");
    
    printf("<h3>GIFPLOT!</h3>");

    printf( "<form name=\"plotform\" method=\"post\" action=\"%s\">\n", this_file);
    
    printf( "<table>\n"
            "<tr><td>p1</td><td width=\"100%\"><input name=\"p1\" type=\"text\" size=\"4\" maxlength=\"4\"></td></tr>\n"
            "<tr><td>p2</td><td width=\"100%\"><input name=\"p2\" type=\"text\" size=\"4\" maxlength=\"4\"></td></tr>\n"
            "<tr><td>&nbsp;</td><td><input type=\"submit\" name=\"submit\" value=\"Go\"></td></tr>\n"
            "</table></form>\n");

    printf("<hr>\n");
    
    printf("blah blah p1 = %d, p2 = %d", p1, p2);

    putenv("LD_LIBRARY_PATH=/usr/local/pgplot");
    
    while (NULL != fopen(LOCK_FILE, "r")) {
        fprintf(stderr, "lock file exists. waiting 1 sec\n");
        sleep(1);
        if (i++ == 5) {
            printf("<p>ERROR - contact core programmers</p></body></html>");
            exit(-1);
        }
    }
    unlink(GIF_FILE); // ???
    
    // what if prog bombs out before removing lock?
    // need to check date of lock file, if older than certain period (a longer period than
    // the program should take to execute, remove it
        
    fp = fopen(LOCK_FILE, "w");
    if (NULL == fp) 
        fprintf(stderr, "error - couldn't open lock file: %s", sys_errlist[errno]);
        
    fclose(fp);
    
    //sleep(4);

    if (fork() == 0)
        execlp("/user/cp/cjb/jim/gifplot/trial_chisq_exec_f_out", "trial_chisq", (char *)0);
    wait(&status);
    
    //plot_();
    
    unlink(LOCK_FILE);

    if (NULL == fopen(LOCK_FILE, "r")) {
        fprintf(stderr, "error2 - ");
        fprintf(stderr, sys_errlist[errno]);
        fprintf(stderr, "<p>lock file removed.</p>");
    }

    
    printf("<img src=\"p.gif\" alt=\"Image.\"></img>\n");
    printf("<hr>\n");
    
    printf("</body></html>");
    
    if (USE_CGI) xcgi_exit();

    return(0);
}
Пример #22
0
void scheduler_FIFO(){

	int i,j,k,timeout,pid,status;
	int * processes_running;
	PROG_T prog;
	char cmd[50];


	i = 0;

	p_sem();
		for(i=0;i<NUM_TAB;i++){
			if((pshm[i].nreq < 0)&&(pshm[i].status == FINISHED)){
				pshm[i].nreq = 0;
				p_sem2();
					/*printf("Liberando antes: %d\n",proc_livres);*/
					proc_livres += pshm[i].num_proc;
					/*printf("Liberando depois: %d\n",proc_livres);*/
				v_sem2();
			}else if((pshm[i].nreq > 0)&&(pshm[i].status == RUNNING)){
				timeout = checkTime(i);
				if(timeout){
					
					sprintf(cmd,"pkill -P %d",pshm[i].pid);
					system(cmd);
					kill(pshm[i].pid,SIGKILL);

					pshm[i].nreq = 0;
					pshm[i].status = FINISHED;
					p_sem2();
						proc_livres += pshm[i].num_proc;
					v_sem2();

				}
			}
		}
	v_sem();

	

	p_sem();

		i = chooseReq();
		
		if((pshm[i].nreq > 0)&&(pshm[i].status == PENDING)&&(pshm[i].num_proc <= proc_livres)){
			
			p_sem2();
			/*printf("Alocando antes: %d\n",proc_livres);*/
			proc_livres -= pshm[i].num_proc;
			/*printf("Alocando depois: %d\n",proc_livres);*/
			v_sem2();

			
			prog.n_params = countParams(pshm[i].proc);
			getArgs(pshm[i],&prog);
			pshm[i].status = RUNNING;

			pid = fork();
			if(pid<0){
				printf("Erro no fork dispatcher\n");
				exit(-1);
			}else if(!pid){
				/*Processo dispatcher*/
				processes_running = (int*)calloc(pshm[i].num_proc,sizeof(int));

				for(j=0;j<pshm[i].num_proc;j++){

					processes_running[j] = fork();
					if(processes_running[j] < 0){
						printf("Erro no fork worker\n");
						exit(-1);
					}else if(processes_running[j] == 0){
						/*Processos worker*/

						execv(prog.nome,prog.params);
					}else{
						/*Processo dispatcher*/

						for(k=0;k<pshm[i].num_proc;k++){
							wait(&status);
							if((k == pshm[i].num_proc-1)&&(j==pshm[i].num_proc-1)){
								pshm[i].status = FINISHED;
								pshm[i].nreq = -1;

								exit(0);
							}
						}
					}
				}
			}else{
				pshm[i].pid = pid;
			}
		}
		
	v_sem();


	for(i=0;i<NUM_TAB;i++){
		if(pshm[i].status == FINISHED){
			waitpid(pshm[i].pid,&status,WNOHANG);
		}
	}

}
Пример #23
0
void send_reply()
{
	char	sample[10];

	myled = 1;

	if (flags.flag_operation_code == 0b01) {
		// the reply contains just the current state
		rn42.putc('*');
		wait(0.1);
		rn42.putc(' ');
		wait(0.1);
		rn42.putc('2');
		wait(0.1);
		rn42.putc(' ');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc(' ');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc(' ');
		wait(0.1);
		rn42.putc('*');
	}
	else if (flags.flag_operation_code == 0b10) {
		// the reply contains state and battery level
		sprintf(sample, "%f", 34.45);		//conversion battery level

		wait(0.1);
		rn42.putc('*');
		wait(0.1);
		rn42.putc(' ');
		wait(0.1);
		rn42.putc('2');
		wait(0.1);
		rn42.putc(' ');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc('#');
		wait(0.1);
		rn42.putc(' ');
		wait(0.1);
		rn42.putc(sample[0]);
		wait(0.1);
		rn42.putc(sample[1]);
		wait(0.1);
		rn42.putc(sample[2]);
		wait(0.1);
		rn42.putc(sample[3]);
		wait(0.1);
		rn42.putc(sample[4]);
		wait(0.1);
		rn42.putc(' ');
		wait(0.1);
		rn42.putc('*');
	}

	myled = 0;
}
Пример #24
0
int
sys_wait(void)
{
  return wait();
}
Пример #25
0
int main(int argc, char **argv)
{
	int i = 0;
	pid_t pid;
	pid_t *childpids = NULL;
	sigset_t sigset;
	int status = 0;
	int ret = 0;

	checkopt(argc,argv);
	if (initialize()) {
		warn("initialize failed");
		report_result("2\n");
		exit(EXIT_FAILURE);
	}

	if (sigemptyset(&sigset) < 0) {
		warn("sigemptyset failed");
		report_result("2\n");
		exit(EXIT_FAILURE);
	}

	childpids = (pid_t *)malloc((nprocs) * sizeof(pid_t));
	if (childpids == NULL) {
		warn("alloc for child pids failed");
		report_result("2\n");
		exit(EXIT_FAILURE);
	}
	memset(childpids, 0, (nprocs) * sizeof(pid_t));

	report_result("0\n");
	sigsuspend(&sigset);
	for (; i < nprocs; i++) {
		pid = fork();
		if (pid == -1) {
			while (--i >= 0)
				kill(childpids[i], SIGKILL);
			warn("fork test tasks failed");
			report_result("2\n");
			exit(EXIT_FAILURE);
		} else if (!pid) {
			ret = cpu_hog();
			exit(ret);
		}
		childpids[i] = pid;
	}

	report_result("0\n");

	while (!end) {
		if (sigemptyset(&sigset) < 0)
			ret = -1;
		else
			sigsuspend(&sigset);

		if (ret || end) {
			for(i = 0; i < nprocs; i++) {
				kill(childpids[i], SIGUSR2);
			}
			break;
		} else {
			for(i = 0; i < nprocs; i++) {
				kill(childpids[i], SIGUSR1);
			}
		}
	}
	for (i = 0; i < nprocs; i++) {
		wait(&status);
		if (status)
			ret = EXIT_FAILURE;
	}

	return ret;
}
Пример #26
0
int main(int argc, char *argv[]) {
  char logfile[BUFFSIZE], filesdir[BUFFSIZE], collectcmd[BUFFSIZE], lscmd[BUFFSIZE], datfile[BUFFSIZE], imgfile[BUFFSIZE];
  FILE *master, *page;
  FILE *sysout;
  char pageline[BUFFSIZE], buff[BUFFSIZE], scmd[BUFFSIZE], pagefile[BUFFSIZE];
  char pageurl[BUFFSIZE], fullurl[BUFFSIZE], *url;
  char urldone;
  pid_t wgetchild;
  time_t waitstart;
  char *data;
  unsigned masterlength, masterloc;
  unsigned pageadds;
  long tester;
  int p;
  int firstentry;

  if (argc != 3 && argc != 4) {
    printf("Usage: web-collage <file> <program>\n");
    exit(-2);
  }

  /* Fill out the commands with name */
  sprintf(logfile, LOG_FILE, argv[1]);
  sprintf(filesdir, FILES_DIR, argv[1]);
  sprintf(collectcmd, COLLECT_CMD, argv[1], argv[1]);
  sprintf(lscmd, LS_CMD, argv[1]);
  sprintf(datfile, DAT_FILE, argv[1]);
  sprintf(imgfile, IMG_FILE, argv[1]);
  /* does the temp directory already exist? */
  mkdir(filesdir, S_IRWXU);

  /* Open File */
  if (!(master = fopen(datfile, "r"))) {
    printf("Creating File...\n");
    
    master = fopen(datfile, "w+");
    if (!master) {
      perror("creating master file");
      exit(-1);
    }

    fprintf(master, "%s\n", argv[3]); /* First URL */
    fclose(master);
  } else
    fclose(master);

  printf("Reading File...\n");

  srand48(time(NULL));

  master = waitreadmaster(datfile, 0, 0, 0); /* READ Lock! */
  fseek(master, 0, SEEK_END);
  masterlength = ftell(master);
  freemaster(datfile, master, 0, 0);      /* Unlock! */

  int iter = 0;
  while (iter++ < 3) {
      /* Get random URL */
      masterloc = lrand48() % masterlength;
      firstentry = 0;
      /* READ Lock! */
      master = waitreadmaster(datfile, masterloc, masterloc, BUFFSIZE);
      fgets(pageurl, BUFFSIZE, master); /* skip to line after random char */
      do
	if (!fgets(pageurl, BUFFSIZE - strlen(collectcmd) - 1, master)) {
	  rewind(master);
	  firstentry = 1;
	  fgets(pageurl, BUFFSIZE - strlen(collectcmd) - 1, master);
	}
      while (pageurl[0] == '\t' || pageurl[0] == '\n');

      if (!firstentry) {
	/* Invalidate URL */
	/* READ->WRITE Lock! */
	master = waitreadtowrite(datfile, master, masterloc, BUFFSIZE);
	fseek(master, -(strlen(pageurl) + 0), SEEK_CUR);
	voidline(master);
      }
      freemaster(datfile, master, masterloc, BUFFSIZE);
      /* Unlock! */

      pageurl[strlen(pageurl) - 1] = '\0';

    printf("\nGetting %s\n", pageurl);

    /* Get webpage, checking for any redirection */
    sprintf(scmd, "%s \"%s\"", collectcmd, pageurl);
    waitstart = time(NULL);
    if (!(wgetchild = fork())) {
      system(scmd);
      exit(0);
    }
    while (validpid(wgetchild) && waitstart + 5 > time(NULL));
    if (validpid(wgetchild))
      kill(wgetchild, 9);
    wait(NULL);
    
    sysout = fopen(logfile, "r");
    if (!sysout)
      continue; /* File does not exist */
    while (fgets(buff, BUFFSIZE, sysout)) {
      printf("%s", buff);
      if (!strncmp(buff, "Location:", 9)) {
	if (strchr(buff + 10, ' '))
	  *strchr(buff + 10, ' ') = '\0';
	strcpy(pageurl, buff + 10);
      }
    }
    fclose(sysout);

    unlink(logfile);

    /* Collect new links */
    sysout = popen(lscmd, "r");
    if (!sysout) {
      perror("searching files directory");
      exit(-3);
    }

    strcpy(pagefile, filesdir);
    if (fgets(pagefile + strlen(pagefile), BUFFSIZE, sysout) != NULL) {
      pagefile[strlen(pagefile) - 1] = '\0';  /* remove newline */
      page = fopen(pagefile, "r");

      addfilename(pageurl, BUFFSIZE, pagefile);

      pageadds = 0;

      /* Write Additional URLs */
      rewind(master);
      if (findlikes(page) || (rand() % KEEP_PROB)) { /* possibly just throw away */
	while (nexttag(pageline, BUFFSIZE, page))
	  if (url = geturl(pageline)) {
	    if (strncasecmp(url, "http://", 7)) {
	      if (!getpath(fullurl, BUFFSIZE, url, pageurl))
		continue;
	    } else
	      strcpy(fullurl, url);
	    /* search for place in file to place */
	    urldone = 0;
	    if (strlen(fullurl) > BUFFSIZE / 2)
	      continue;  /* too big, don't add */
	    if (rand() % (pageadds + 1) > KEEP_PROB)
	      continue;  /* add fewer urls as more on page */
	    if (strstr(fullurl, ".com") && rand() % DROP_PROB)
	      continue;  /* only chance to add a .com link */
	    if ((strstr(fullurl, "yahoo.com") ||
		 strstr(fullurl, "www.google.com")) && rand() % DROP_PROB)
	      continue;  /* almost no yahoo.com's, www.google.com's */
	    for (p = 0; p < DISLIKE_CNT; p++)
	      if (strstr(fullurl, dislikes[p])) /* just skip */
		continue;
	    /* READ Lock! */
	    master = waitreadmaster(datfile, 0, 0, 0);
	    while (fgets(buff, BUFFSIZE, master)) {
	      if (!strncmp(buff, fullurl, strlen(fullurl)) ||
		  (!strncmp(buff, fullurl, strchr(buff + strlen("http://"), '/')
			    - buff) && !(rand() % HOST_CROWD))) {
		urldone = 1;
		freemaster(datfile, master, 0, 0);
		/* Unlock! */
		break;
	      }
	      if (buff[0] == '\t' || buff[0] == '\n')
		if (strlen(buff) >= strlen(fullurl) + 1) {
		  masterloc = ftell(master);
		  freemaster(datfile, master, 0, 0);
		  /* Unlock! */
		  printf("Adding %s\n", fullurl);
		  pageadds++;
		  /* WRITE Lock! */
		  waitwritemaster(datfile, masterloc - strlen(buff), 
				  masterloc - strlen(buff), BUFFSIZE);
		  fprintf(master, "%s\n", fullurl);
		  if (strlen(buff) >= strlen(fullurl) + 2)
		    fputc('\t', master);
		  fseek(master, 0, SEEK_END);
		  masterlength = ftell(master);
		  freemaster(datfile, master,
			     masterloc - strlen(buff), BUFFSIZE);
		  /* Unlock! */
		  urldone = 1;
		  break;
		}
	    }
	    if (!urldone) {
	      if (ftell(master) > MAX_SIZE) { /* too big, just remove entries */
		fseek(master, lrand48() % ftell(master), SEEK_SET);
		fgets(buff, BUFFSIZE, master);
		urldone = 1;  /* flag that was greater than MAX_SIZE */
	      }
	      masterloc = ftell(master);
	      freemaster(datfile, master, 0, 0);
	      /* Unlock! */
	      printf("Adding %s\n", fullurl);
	      pageadds++;
	      /* WRITE Lock! */
	      waitwritemaster(datfile, masterloc, masterloc - 2, BUFFSIZE);
	      fprintf(master, "%s\n", fullurl);
	      if (urldone)
		voidline(master);
	      fseek(master, 0, SEEK_END);
	      masterlength = ftell(master);
	      freemaster(datfile, master, masterloc - 2, BUFFSIZE);
	      /* Unlock! */
	    }
	  }
      }

      fclose(page);

      /* Move file to final destination */
      sprintf(scmd, "%s \"%s\" \"%s\"", argv[2], argv[1], pagefile);
      system(scmd);
      sleep(WAIT_TIME);
      sprintf(scmd, "touch %sREMOVE.tmp", filesdir);
      system(scmd);
      sprintf(scmd, "rm %s*", filesdir);
      system(scmd);
    }

    pclose(sysout);
  }
}
Пример #27
0
void run() {
    // Continue execution of the stopped child process.
    std::cerr << "Resuming execution" << std::endl;
    CHECK(ptrace(PT_CONTINUE, pid, (caddr_t)1, 0));
    wait(NULL);
}
Пример #28
0
int MapUpdater::deactivate() {
	wait();

	return m_executor.deactivate();
}
Пример #29
0
static int
check_pids(struct tag_pgrp *running, int *num_active, int keep_active,
	   FILE * logfile, FILE * failcmdfile, struct orphan_pgrp *orphans,
	   int fmt_print, int *failcnt, int quiet_mode)
{
    int w;
    pid_t cpid;
    int stat_loc;
    int ret = 0;
    int i;
    time_t t;
    char *status;
    int signaled = 0;
    struct tms tms1, tms2;
    clock_t tck;

    check_orphans(orphans, 0);

    tck = times(&tms1);
    if (tck == -1) {
	fprintf(stderr, "pan(%s): times(&tms1) failed.  errno:%d  %s\n",
		panname, errno, strerror(errno));
    }
    cpid = wait(&stat_loc);
    tck = times(&tms2);
    if (tck == -1) {
	fprintf(stderr, "pan(%s): times(&tms2) failed.  errno:%d  %s\n",
		panname, errno, strerror(errno));
    }

    if (cpid < 0) {
	if (errno == EINTR) {
	    if (Debug)
		fprintf(stderr, "pan(%s): wait() interrupted\n", panname);
	} else if (errno != ECHILD) {
	    fprintf(stderr, "pan(%s): wait() failed.  errno:%d  %s\n",
		    panname, errno, strerror(errno));
	}
    } else if (cpid > 0) {

	if (WIFSIGNALED(stat_loc)) {
	    w = WTERMSIG(stat_loc);
	    status = "signaled";
	    if (Debug & Dexit)
		fprintf(stderr, "child %d terminated with signal %d\n", cpid,
			w);
	    --*num_active;
	    signaled = 1;
	} else if (WIFEXITED(stat_loc)) {
	    w = WEXITSTATUS(stat_loc);
	    status = "exited";
	    if (Debug & Dexit)
		fprintf(stderr, "child %d exited with status %d\n", cpid, w);
	    --*num_active;
	    if (w != 0)
		ret++;
	} else if (WIFSTOPPED(stat_loc)) {	/* should never happen */
	    w = WSTOPSIG(stat_loc);
	    status = "stopped";
	    ret++;
	} else {		/* should never happen */
	    w = 0;
	    status = "unknown";
	    ret++;
	}

	for (i = 0; i < keep_active; ++i) {
	    if (running[i].pgrp == cpid) {
		if ((w == 130) && running[i].stopping &&
		    (strcmp(status, "exited") == 0)) {
		    /* The child received sigint, but
		     * did not trap for it?  Compensate
		     * for it here.
		     */
		    w = 0;
		    ret--;	/* undo */
		    if (Debug & Drunning)
			fprintf(stderr,
				"pan(%s): tag=%s exited 130, known to be signaled; will give it an exit 0.\n",
				panname, running[i].cmd->name);
		}
		time(&t);
		if (logfile != NULL) {
			if (!fmt_print)
				fprintf(logfile,
				 "tag=%s stime=%d dur=%d exit=%s stat=%d core=%s cu=%d cs=%d\n",
					running[i].cmd->name, (int) (running[i].mystime),
					(int) (t - running[i].mystime), status, w,
					(stat_loc & 0200) ? "yes" : "no",
					(int) (tms2.tms_cutime - tms1.tms_cutime),
					(int) (tms2.tms_cstime - tms1.tms_cstime));
			else
			{
					if (w != 0) 
						++*failcnt;
					fprintf(logfile, "%-30.30s %-10.10s %-5d\n", 
							running[i].cmd->name, ((w != 0) ? "FAIL" : "PASS"),
							w);
			}

			fflush(logfile);
		}

		if ((failcmdfile != NULL) && (w !=0)) {
			fprintf(failcmdfile, "%s %s\n", running[i].cmd->name, running[i].cmd->cmdline);
		}

		if (running[i].stopping)
		    status = "driver_interrupt";

		if (test_out_dir) {
			if (!quiet_mode)
				write_test_start(running+i);
			copy_buffered_output(running + i);
			unlink(running[i].output);
		}
		if (!quiet_mode)
			write_test_end(running+i, "ok", t, status,
			   stat_loc, w, &tms1, &tms2);

		/* If signaled and we weren't expecting
		 * this to be stopped then the proc
		 * had a problem.
		 */
		if (signaled && !running[i].stopping)
		    ret++;

		running[i].pgrp = 0;
		if (zoo_clear(zoofile, cpid)) {
		    fprintf(stderr, "pan(%s): %s\n", panname, zoo_error);
		    exit(1);
		}

		/* Check for orphaned pgrps */
		if ((kill(-cpid, 0) == 0) || (errno == EPERM)) {
		    if (zoo_mark_cmdline(zoofile, cpid, "panorphan",
					  running[i].cmd->cmdline)) {
			fprintf(stderr, "pan(%s): %s\n", panname, zoo_error);
			exit(1);
		    }
		    mark_orphan(orphans, cpid);
		    /* status of kill doesn't matter */
		    kill(-cpid, SIGTERM);
		}

		break;
	    }
	}
    }
    return ret;
}
Пример #30
0
static void dumpBacktrace( unsigned int depth )
{
  if ( depth == 0 )
    depth = 20;

#if ((defined(linux) || defined(__linux__)) && !defined(ANDROID)) || defined(__FreeBSD__)
  // Below there is a bunch of operations that are not safe in multi-threaded
  // environment (dup()+close() combo, wait(), juggling with file descriptors).
  // Maybe some problems could be resolved with dup2() and waitpid(), but it seems
  // that if the operations on descriptors are not serialized, things will get nasty.
  // That's why there's this lovely mutex here...
  static QMutex mutex;
  QMutexLocker locker( &mutex );

  int stderr_fd = -1;
  if ( access( "/usr/bin/c++filt", X_OK ) < 0 )
  {
    myPrint( "Stacktrace (c++filt NOT FOUND):\n" );
  }
  else
  {
    int fd[2];

    if ( pipe( fd ) == 0 && fork() == 0 )
    {
      close( STDIN_FILENO ); // close stdin

      // stdin from pipe
      if ( dup( fd[0] ) != STDIN_FILENO )
      {
        QgsDebugMsg( "dup to stdin failed" );
      }

      close( fd[1] );        // close writing end
      execl( "/usr/bin/c++filt", "c++filt", static_cast< char * >( nullptr ) );
      perror( "could not start c++filt" );
      exit( 1 );
    }

    myPrint( "Stacktrace (piped through c++filt):\n" );
    stderr_fd = dup( STDERR_FILENO );
    close( fd[0] );          // close reading end
    close( STDERR_FILENO );  // close stderr

    // stderr to pipe
    int stderr_new = dup( fd[1] );
    if ( stderr_new != STDERR_FILENO )
    {
      if ( stderr_new >= 0 )
        close( stderr_new );
      QgsDebugMsg( "dup to stderr failed" );
    }

    close( fd[1] );  // close duped pipe
  }

  void **buffer = new void *[ depth ];
  int nptrs = backtrace( buffer, depth );
  backtrace_symbols_fd( buffer, nptrs, STDERR_FILENO );
  delete [] buffer;
  if ( stderr_fd >= 0 )
  {
    int status;
    close( STDERR_FILENO );
    int dup_stderr = dup( stderr_fd );
    if ( dup_stderr != STDERR_FILENO )
    {
      close( dup_stderr );
      QgsDebugMsg( "dup to stderr failed" );
    }
    close( stderr_fd );
    wait( &status );
  }
#elif defined(Q_OS_WIN)
  void **buffer = new void *[ depth ];

  SymSetOptions( SYMOPT_DEFERRED_LOADS | SYMOPT_INCLUDE_32BIT_MODULES | SYMOPT_UNDNAME );
  SymInitialize( GetCurrentProcess(), "http://msdl.microsoft.com/download/symbols;http://download.osgeo.org/osgeo4w/symstore", TRUE );

  unsigned short nFrames = CaptureStackBackTrace( 1, depth, buffer, nullptr );
  SYMBOL_INFO *symbol = ( SYMBOL_INFO * ) qgsMalloc( sizeof( SYMBOL_INFO ) + 256 );
  symbol->MaxNameLen = 255;
  symbol->SizeOfStruct = sizeof( SYMBOL_INFO );
  IMAGEHLP_LINE *line = ( IMAGEHLP_LINE * ) qgsMalloc( sizeof( IMAGEHLP_LINE ) );
  line->SizeOfStruct = sizeof( IMAGEHLP_LINE );

  for ( int i = 0; i < nFrames; i++ )
  {
    DWORD dwDisplacement;
    SymFromAddr( GetCurrentProcess(), ( DWORD64 )( buffer[ i ] ), 0, symbol );
    symbol->Name[ 255 ] = 0;
    if ( SymGetLineFromAddr( GetCurrentProcess(), ( DWORD64 )( buffer[i] ), &dwDisplacement, line ) )
    {
      myPrint( "%s(%d) : (%s) frame %d, address %x\n", line->FileName, line->LineNumber, symbol->Name, i, symbol->Address );
    }
    else
    {
      myPrint( "%s(%d) : (%s) unknown source location, frame %d, address %x [GetLastError()=%d]\n", __FILE__, __LINE__, symbol->Name, i, symbol->Address, GetLastError() );
    }
  }

  qgsFree( symbol );
  qgsFree( line );
#else
  Q_UNUSED( depth );
#endif
}