Exemplo n.º 1
0
int64_t ForkWrapper::read_result()
{
	unsigned char buffer[sizeof(int64_t) + sizeof(int)];
//printf("ForkWrapper::read_result %d  parent_fd=%d\n", __LINE__, parent_fd);

	if(read_timeout(buffer, sizeof(buffer))) return 1;
//printf("ForkWrapper::read_result %d  parent_fd=%d\n", __LINE__, parent_fd);
	int64_t *lbfr = (int64_t *)buffer;
	int64_t result = lbfr[0];
	int *ibfr = (int *)&lbfr[1];
	result_bytes = ibfr[0];

	if(result_bytes && result_allocated < result_bytes)
	{
		delete [] result_data;
		result_data = new unsigned char[result_bytes];
		result_allocated = result_bytes;
	}
//printf("ForkWrapper::read_result %d  parent_fd=%d result=" _LD " result_bytes=%d\n", 
//__LINE__, 
//parent_fd,
//result,
//result_bytes);

	if(result_bytes) 
		if(read_timeout(result_data, result_bytes)) return 1;
//printf("ForkWrapper::read_result %d  parent_fd=%d\n", __LINE__, parent_fd);

	return result;
}
Exemplo n.º 2
0
ssize_t read_timeout_usec(int fd, void * buf, size_t count, long usec_timeout)
{
    struct timeval timeout;
    timeout.tv_sec = 0;
    timeout.tv_usec = usec_timeout;
    return read_timeout(fd, buf, count, &timeout);
}
Exemplo n.º 3
0
void read_string(char **ptr, unsigned long *left, unsigned long cnt)
{
	if (imap_readptrleft == 0)
	{
		/* Keep reading until we fill the buffer or until we've
		** read the entire string.
		*/

		read_timeout(SOCKET_TIMEOUT);
		imap_readptr=readbuf;
		while (imap_readptrleft < sizeof(readbuf) && imap_readptrleft < cnt)
			imap_readptrleft += doread(readbuf+imap_readptrleft,
						sizeof(readbuf)-imap_readptrleft);
	}

	if (cnt < imap_readptrleft)	/* Can satisfy fully from buffer */
	{
		*ptr=imap_readptr;
		*left=cnt;
		imap_readptr += cnt;
		imap_readptrleft -= cnt;
		return;
	}

	*ptr=imap_readptr;
	*left=imap_readptrleft;
	imap_readptrleft=0;
	return;
}
Exemplo n.º 4
0
int read_line_timeout_ex(int fd, void *buf_in, int maxlen, int msTimeout, int *timed_out)
{
    int len=0;
    int thislen;
    char *buf=(char*) buf_in;

    *timed_out = 0;

    while (len<maxlen)
    {
        thislen=read_timeout(fd, &buf[len], 1, msTimeout);
        if (thislen < 0)
            return thislen;
        if (thislen==0) {
            *timed_out = 1;
            return 0;
        }

        if (buf[len]=='\n' || buf[len]=='\r')
        {
            buf[len]=0;
            return len;
        }

        len++;
    }

    buf[len]=0;
    return len;
}
Exemplo n.º 5
0
/* reads response, ignores fscking carriage returns */
static int http_read_response(int fd, char **bufp, int *sizep, int *posp, int timeout_ms)
{
	if (read_timeout(fd, timeout_ms))
		return -1;
	while (1) {
		char *buf = *bufp;
		int pos = *posp;
		int rc;
		char ch;

		rc = read(fd, &ch, 1);
		if (rc == -1) {
			return -1;
		}
		if (rc == 0) {
			return -2;
		}
		if (ch == '\r')
			continue;
		if (ch == '\n' && pos > 0 && buf[pos - 1] == '\n') {
			buf_write_ch(bufp, sizep, posp, 0);
			return 0;
		}
		buf_write_ch(bufp, sizep, posp, ch);
	}
}
Exemplo n.º 6
0
void PinchGloveStandalone::sendCommand(const vpr::Uint8& first,
                                       const vpr::Uint8& second)
{
    unsigned char buf[10];

    vpr::Interval read_timeout(100,vpr::Interval::Msec);

    mPort->flushQueue(vpr::SerialTypes::IO_QUEUES);

    // If there was already a byte in the PinchGlove's input buffer
    // the hardware will get the last byte and return a '?' because
    // it is confused. If we can read this, we need to fix it. In a
    // way we are clearing the PinchGloves input buffer.

    mPort->write(&first, 1);
    try
    {
        mPort->read(&buf[0], 10, read_timeout);
        // If read without an error.
        mPort->write(&first, 1);
    }
    catch (vpr::IOException&)
    {
        // Do nothing.
    }
    vpr::System::msleep(100);
    // Wait between sending bytes.
    mPort->write(&second, 1);
}
Exemplo n.º 7
0
ssize_t
readn(int fp,void *buf,size_t count)
{
	int ret = 0;
	//这里按照read调用的方式来封转
	size_t nleft = count;
	ssize_t nread;

	char *bufp = (char *)buf;
	while(nleft > 0) {
		//进行超时判断
		if((ret = read_timeout(fp,5)) < 0) {
			//timeout
			return ret;
		}
		if((nread = read(fp,bufp,nleft)) < 0) {
			//小于0有几种情况
			if(errno == EINTR) {//这个是被信号中断不认为错
				continue;
			} 
			//其它错误都直接返回失败
			return nread;
		} else if(0 == nread) {
			return count - nleft;//返回当前读取到的实际数据
		}
		//剩下的情况就是正常读取了数据
		bufp += nread;
		nleft -= nread;
	}
	//返回所有数据
	return count;
}
Exemplo n.º 8
0
/* Return values:
 * Negative on error
 * 0 on success with a reusable socket
 * 1 on success with a non-reusable socket */
static int handle_request(int client, uid_t uid)
{
	request_header req;
	ssize_t got;
	char buffer[NSCD_MAXKEYLEN];
	
	/* read the request header, but time out after a short while */
	got = read_timeout(client, &req, sizeof(req), LONG_TIMEOUT, 1);
	if(debug)
	{
		if(got < 0)
		{
			if(errno == ETIMEDOUT)
				printf("Client %d timed out\n", client);
			else if(errno == ECONNRESET)
				printf("Client %d closed by peer\n", client);
			else
				printf("Client %d error (%s)\n", client, strerror(errno));
		}
		else if(!got)
			printf("Client %d completed\n", client);
	}
	if(got != sizeof(req) || req.version != NSCD_VERSION)
		return -1;
	
	/* glibc nscd limits the key to 1024 bytes, so we will too */
	if(req.key_len < 0 || req.key_len > NSCD_MAXKEYLEN)
		return -1;
	
	if(req.key_len)
	{
		/* read the key, but again time out after a (shorter) while */
		got = read_timeout(client, buffer, req.key_len, SHORT_TIMEOUT, 1);
		if(got != req.key_len)
			return -1;
		/* the last character of the key should be null */
		if(buffer[req.key_len - 1])
			return -1;
	}
	else
		buffer[0] = 0;
	
	return process_request(client, uid, &req, buffer);
}
Exemplo n.º 9
0
int CiA301CommPort::WaitForReadMessage(co_msg & output, unsigned int canIndex){

    can_msg input;
//    cout<<"WaitForReadMessage -----------" << endl;


#if USE_TIMEOUT
    if(read_timeout(portFileDescriptor,&input,USE_TIMEOUT)==0)
    {
        //err(1,"Could not read the message.");
        return -1;
    }

#else //(NOT)USE_TIMEOUT
    if( read(portFileDescriptor,&input,sizeof(struct can_msg) !=sizeof(input)) )
    {
        err(1,"read");
    }
#endif //USE_TIMEOUT


    //convert received data to canopen
    if(CanBusToCanOpen(input, output)!=0)
    {
       err(1,"error al convertir el mensaje");
       return -1;
    }
    else
    {
//        //print can frame information
//        cout<<"received can id " << (bitset<16>)input.id << " rtr: " << input.rtr << endl;
//        cout<<"received data: ";
//        for (int i = 0; i < input.dlc; i++)
//        {

//            printf("%02x ",input.data[i]);
//        }
//        cout<<endl;
//                cout<<"received cob id " << std::hex << output.id_co << std::dec << " rtr: " << output.rtr << endl;
//                cout<<"received canopen data: ";
//                for (int i = 0; i < output.dlc_co; i++)
//                {

//                    printf("%02x ",output.data_co[i]);
//                }
//                cout<<endl;
//                cout<<"WaitForReadMessage End-----------" << endl;
    }
    return 0;
}
Exemplo n.º 10
0
static char *send_auth_reply(const char *q, void *dummy)
{
	struct imaptoken *tok;
	char	*p;

#if SMAP
	const char *cp=getenv("PROTOCOL");

	if (cp && strcmp(cp, "SMAP1") == 0)
		writes("> ");
	else
#endif

	{
		writes("+ ");
	}
	writes(q);
	writes("\r\n");
	writeflush();
	read_timeout(SOCKET_TIMEOUT);
	tok=nexttoken_nouc();

	switch (tok->tokentype)	{
	case IT_ATOM:
	case IT_NUMBER:
		p=my_strdup(tok->tokenbuf);
		break;
	case IT_EOL:
		p=my_strdup("");
		break;
	default:
		return (0);
	}
	if (!p)
	{
		perror("malloc");
		return (0);
	}

	if (nexttoken()->tokentype != IT_EOL)
	{
		free(p);
		fprintf(stderr, "Invalid SASL response\n");
		return (0);
	}
	read_eol();
	return (p);
}
Exemplo n.º 11
0
int main(int argc, char **argv)
{
    int timeout;
    pid_t pid;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <seconds> <program> [...]\n",
                argv[0]);
        return EXIT_FAILURE;
    }

    timeout = read_timeout(argv[1]);
    pid = spawn(argv+2);
    start_alarm(timeout);
    wait_alarm(pid);
    return EXIT_SUCCESS;
}
Exemplo n.º 12
0
/* returns -1 on error, nchar on timeout or success. */
int read_fully_timeout(int fd, void *bufin, int len, int msTimeout)
{
    char *buf=(char*) bufin;
    int readsofar=0;
    int thisread=0;

    while (readsofar<len)
    {
        thisread=read_timeout(fd, &buf[readsofar], len-readsofar, msTimeout);
        if (thisread == 0)
            return readsofar;
        if (thisread < 0)
            return thisread;

        readsofar+=thisread;
    }

    return len;
}
Exemplo n.º 13
0
int sckClient_rcv(void *handle, unsigned char *out, int *outlen)
{
    int ret = 0;
    SckHandle *tmp = handle;
    ret = read_timeout(tmp->sockfd, tmp->recvtime);
    if(ret < 0){
        if(ret == -1 && errno == ETIMEDOUT){
            ret = SCK_ERRTIMEOUT;
            printf("sckClient_rcv() err: %d\n", ret);
            return ret;
        }

        return ret;
    }
    int netdatalen = 0;
    ret = readn(tmp->sockfd, &netdatalen, 4);
    if(ret == -1 ){
        printf("func sckClient_rcv() first err: %d\n", ret);
        return ret;
    }else if(ret < 4){
        ret = SCK_ERRPEERCLOSED;
        printf("func sckClient_rcv() first err: %d\n", ret);
        return ret;
    }
    int n;
    n = ntohl(netdatalen);
    ret = readn(tmp->sockfd, out, n);
    if(ret == -1 ){
        printf("func sckClient_rcv() second err: %d\n", ret);
        return ret;
    }else if(ret < n){
        ret = SCK_ERRPEERCLOSED;
        printf("func sckClient_rcv() second err: %d\n", ret);
        return ret;
    }
    *outlen = n;

    return 0;
}
Exemplo n.º 14
0
int sckServer_rcv(int connfd, unsigned char *out, int *outlen, int timeout){
    int ret = 0;
	printf("sckServer_rcv() connfd=%d\n", connfd);
    ret = read_timeout(connfd, timeout);
    if(ret < 0){
        if(ret == -1 && errno == ETIMEDOUT){
            ret = SCK_ERRTIMEOUT;
            printf("sckServer_rcv() read timeout err: %d\n", ret);
            return ret;
        }

        return ret;
    }
    int netdatalen = 0;
    ret = readn(connfd, &netdatalen, 4);
    if(ret == -1 ){
        printf("func sckServer_rcv() first err: %d\n", ret);
        return ret;
    }else if(ret < 4){
        ret = SCK_ERRPEERCLOSED;
        printf("func sckServer_rcv() first err: %d\n", ret);
        return ret;
    }
    int n;
    n = ntohl(netdatalen);
    ret = readn(connfd, out, n);
    if(ret == -1 ){
        printf("func sckServer_rcv() second err: %d\n", ret);
        return ret;
    }else if(ret < n){
        ret = SCK_ERRPEERCLOSED;
        printf("func sckServer_rcv() second err: %d\n", ret);
        return ret;
    }
    *outlen = n;

    return 0;
}
Exemplo n.º 15
0
void PinchGloveStandalone::readData(std::vector<vpr::Uint8>& result,
                                    const vpr::Uint8& data_type)
{
    vpr::Uint32 read;
    vpr::Uint8  temp_byte;

    vpr::Interval read_timeout(5000,vpr::Interval::Msec);

    try
    {
        read = mPort->read(&temp_byte, 1, read_timeout);
    }
    catch (vpr::IOException&)
    {
        // TODO: setCause(ex)
        throw PinchGlove::TimeoutException("[PinchGlove] Timeout occured while trying to read.");
    }
    vprASSERT(1 == read);

    while(data_type != temp_byte)
    {
        try
        {
            read = mPort->read(&temp_byte, 1, read_timeout);
        }
        catch (vpr::IOException&)
        {
            // TODO: setCause(ex)
            throw PinchGlove::TimeoutException("[PinchGlove] Timeout occured while trying to read.");
        }
        vprASSERT(1 == read);
    }

    // Getting all chars until END_BYTE
    result.clear();

    try
    {
        read = mPort->read(&temp_byte, 1, read_timeout);
    }
    catch (vpr::IOException&)
    {
        // TODO: setCause(ex)
        throw PinchGlove::TimeoutException("[PinchGlove] Timeout occured while trying to read.");
    }
    vprASSERT(1 == read);

    // Getting all chars until END_BYTE
    while( PinchGlove::Control::END_BYTE != temp_byte)
    {
        // Add the byte to the result.
        result.push_back(temp_byte);

        try
        {
            read = mPort->read(&temp_byte, 1, read_timeout);
        }
        catch (vpr::IOException&)
        {
            // TODO: setCause(ex)
            throw PinchGlove::TimeoutException("[PinchGlove] Timeout occured while trying to read.");
        }
        vprASSERT(1 == read);
    }
}
Exemplo n.º 16
0
static int get_command(int fd)
{
	int length;
	char buffer[PACKET_SIZE + 1], backup[PACKET_SIZE + 1];
	char* end;
	int packet_length, i;
	char* directive;

	length = read_timeout(fd, buffer, PACKET_SIZE, 0);
	packet_length = 0;
	while (length > packet_length) {
		buffer[length] = 0;
		end = strchr(buffer, '\n');
		if (end == NULL) {
			log_error("bad send packet: \"%s\"", buffer);
			/* remove clients that behave badly */
			return 0;
		}
		end[0] = 0;
		log_trace("received command: \"%s\"", buffer);
		packet_length = strlen(buffer) + 1;

		strcpy(backup, buffer);
		strcat(backup, "\n");
		directive = strtok(buffer, WHITE_SPACE);
		if (directive == NULL) {
			if (!send_error(fd, backup, "bad send packet\n"))
				return 0;
			goto skip;
		}
		for (i = 0; directives[i].name != NULL; i++) {
			if (strcasecmp(directive, directives[i].name) == 0) {
				if (!directives[i].function(fd, backup, strtok(NULL, "")))
					return 0;
				goto skip;
			}
		}

		if (!send_error(fd, backup, "unknown directive: \"%s\"\n", directive))
			return 0;
skip:
		if (length > packet_length) {
			int new_length;

			memmove(buffer, buffer + packet_length, length - packet_length + 1);
			if (strchr(buffer, '\n') == NULL) {
				new_length = read_timeout(fd, buffer + length -
							  packet_length, PACKET_SIZE - (length - packet_length), 5);
				if (new_length > 0)
					length = length - packet_length + new_length;
				else
					length = new_length;
			} else {
				length -= packet_length;
			}
			packet_length = 0;
		}
	}

	if (length == 0)        /* EOF: connection closed by client */
		return 0;
	return 1;
}
Exemplo n.º 17
0
static void process_manager_thread_function_init_new_child(struct thread_init_new_child_args *tinfo)
{
    assert(tinfo);
    const pid_t pid = tinfo->pid;
    assert(pid > 0);
    const char *projname = tinfo->project_name;
    assert(projname);
    const pthread_t thread_id = pthread_self();
    char *buffer = NULL;
    int retval;
    int has_child_crash = 0;
    int len;
    struct fcgi_message_s *message = NULL;

    db_process_set_state_init(pid, thread_id);


    debug(1, "init new spawned child process for project '%s'", projname);


//    char debugfile[256];
//    sprintf(debugfile, "/tmp/threadinit.%lu.dump", thread_id);
//    int debugfd = open(debugfile, (O_WRONLY|O_CREAT|O_TRUNC), (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH));
//    if (-1 == debugfd)
//    {
//	debug(1, "ERROR: can not open file '%s': ", debugfile);
//	logerror(NULL);
//	qexit(EXIT_FAILURE);
//    }


    /* open the socket to the child process */

    struct sockaddr_un sockaddr;
    socklen_t sockaddrlen = sizeof(sockaddr);
    int childunixsocketfd = db_get_process_socket(pid);

    retval = getsockname(childunixsocketfd, (struct sockaddr *)&sockaddr, &sockaddrlen);
    if (-1 == retval)
    {
	logerror("ERROR: retrieving the name of child process socket %d", childunixsocketfd);
	has_child_crash = 1;
    }
    /* leave the original child socket and create a new one on the opposite
     * side.
     * create the socket in blocking mode (non SOCK_NONBLOCK) because we need the
     * read() and write() calls waiting on it.
     */
    if (!has_child_crash)
    {
	retval = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
	if (-1 == retval)
	{
	    logerror("ERROR: can not create socket to child process");
	    has_child_crash = 1;
	}
    }
    if (!has_child_crash)
    {
	childunixsocketfd = retval;	// refers to the socket this program connects to the child process
	retval = connect(childunixsocketfd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
	if (-1 == retval)
	{
	    logerror("ERROR: init can not connect to child process");
	    has_child_crash = 1;
	}
    }
//    debug(1, "init project '%s', connected to child via socket '\\0%s'", projname, sockaddr.sun_path+1);


    static const int maxbufferlen = 4096;
    static const int requestid = 1;
    if (!has_child_crash)
    {
	/* create the fcgi data and
	 * send the fcgi data to the child process
	 */
	buffer = malloc(maxbufferlen);
	assert(buffer);
	if ( !buffer )
	{
	    logerror("ERROR: could not allocate memory");
	    qexit(EXIT_FAILURE);
	}

	message = fcgi_message_new_begin(requestid, FCGI_RESPONDER, 0);
	len = fcgi_message_write(buffer, maxbufferlen, message);
	if (-1 == len)	// TODO: be more flexible if buffer too small
	{
	    debug(1, "fcgi message buffer too small (%d)", maxbufferlen);
	    qexit(EXIT_FAILURE);
	}
//	retval = write(debugfd, buffer, len);
	retval = write(childunixsocketfd, buffer, len);
	if (-1 == retval)
	{
	    logerror("ERROR: can not write to child process");
	    has_child_crash = 1;
	}
	//printf(stderr, "write to child prog (%d): %.*s\n", retval, buffer, retval);
	fcgi_message_delete(message);
    }

    if (!has_child_crash)
    {
	char *parambuffer = (char *)buffer;
	int remain_len = maxbufferlen;

	int i;
	for (i=0; i<128; i++)
	{
	    const char *key = config_get_init_key(projname, i);
	    if (!key)
		break;
	    const char *value = config_get_init_value(projname, i);
	    if (!value)
		break;
	    debug(1, "Param %s=%s", key, value);

	    retval = fcgi_param_list_write(parambuffer, remain_len, key, value);
	    if (-1 == retval)
	    {
		// TODO: be more flexible if buffer too small
		debug(1, "fcgi parameter buffer too small (%d)", maxbufferlen);
		qexit(EXIT_FAILURE);

	    }

	    parambuffer += retval;
	    remain_len -= retval;

	}
	len = maxbufferlen - remain_len;

	if (i>=128)
	{
	    debug(1, "fcgi parameter too many key/value pairs");
	    has_child_crash = 1;
	}
    }

    if (!has_child_crash)
    {
	/* send parameter list */
	message = fcgi_message_new_parameter(requestid, buffer, len);
	len = fcgi_message_write(buffer, maxbufferlen, message);
	if (-1 == len)	// TODO: be more flexible if buffer too small
	{
	    debug(1, "fcgi message buffer too small (%d)", maxbufferlen);
	    qexit(EXIT_FAILURE);
	}
//	retval = write(debugfd, buffer, len);
	retval = write(childunixsocketfd, buffer, len);
	if (-1 == retval)
	{
	    logerror("ERROR: can not write to child process");
	    has_child_crash = 1;
	}
	fcgi_message_delete(message);
    }

    if (!has_child_crash)
    {
	/* send empty parameter list to signal EOP */
	message = fcgi_message_new_parameter(requestid, "", 0);
	len = fcgi_message_write(buffer, maxbufferlen, message);
	if (-1 == len)	// TODO: be more flexible if buffer too small
	{
	    debug(1, "fcgi message buffer too small (%d)", maxbufferlen);
	    qexit(EXIT_FAILURE);
	}
//	retval = write(debugfd, buffer, len);
	retval = write(childunixsocketfd, buffer, len);
	if (-1 == retval)
	{
	    logerror("ERROR: can not write to child process");
	    has_child_crash = 1;
	}
	fcgi_message_delete(message);
    }

    if (!has_child_crash)
    {
	message = fcgi_message_new_stdin(requestid, "", 0);
	len = fcgi_message_write(buffer, maxbufferlen, message);
	if (-1 == len)
	{
	    debug(1, "fcgi message buffer too small (%d)", maxbufferlen);
	    qexit(EXIT_FAILURE);
	}
//	retval = write(debugfd, buffer, len);
	retval = write(childunixsocketfd, buffer, len);
	if (-1 == retval)
	{
	    logerror("ERROR: can not write to child process");
	    has_child_crash = 1;
	}
	// write stdin = "" twice
	if (!has_child_crash)
	{
//	    retval = write(debugfd, buffer, len);
	    retval = write(childunixsocketfd, buffer, len);
	    if (-1 == retval)
	    {
		logerror("ERROR: can not write to child process");
		has_child_crash = 1;
	    }
	}
	fcgi_message_delete(message);
    }

    if (!has_child_crash)
    {
	/* now read from socket into void until no more data
	 * we do it to make sure that the child process has completed the request
	 * and filled up its cache.
	 *
	 * Set a timeout of N seconds in case the program crashed during start. If
	 * the timeout catches move the process to the shutdown module and in the
	 * database mark the process as crashed.
	 */
	const int init_read_timeout = config_get_read_timeout(projname);
	retval = 1;
	while (retval>0)
	{
	    retval = read_timeout(childunixsocketfd, buffer, maxbufferlen, init_read_timeout*1000);
//	    debug(1, "init project '%s' received:\n%.*s", projname, retval, buffer);
	    if (-1 == retval)
	    {
		logerror("ERROR: read() from child process during init phase");
		if (ETIMEDOUT == errno)
		{
		    has_child_crash = 1;
		}
	    }
	}
    }

    /* if the child process died during the initialization we need to figure
     * this out.
     * there may be a race condition between the signal handler and this thread
     * so we test the existence of the child process after the read.
     */
    if (has_child_crash)
    {
	printlog("starting new process for project %s", projname);
	process_manager_restart_process(pid);
	process_manager_process_died_during_init(pid, projname);
    }
    else
    {
	retval = kill(pid, 0);
	if (-1 == retval)
	{
	    if (ESRCH == errno)
	    {
		/* child process died during initialization.
		 * start a new one if possible
		 */
		process_manager_process_died_during_init(pid, projname);
	    }
	    else
	    {
		logerror("ERROR: kill(%d,0) returned", pid);
		qexit(EXIT_FAILURE);
	    }
	}
	else
	{
	    db_process_set_state_idle(pid);
	}
    }

    /* ok, we did read each and every byte from child process.
     * now close this and set idle
     * Try to close the file secriptor even if error occurred previously
     */
    retval = close(childunixsocketfd);
    debug(1, "closed child socket fd %d, retval %d, errno %d", childunixsocketfd, retval, errno);
//    close(debugfd);
    debug(1, "init child process for project '%s' done. waiting for input..", projname);


    free(buffer);
}
Exemplo n.º 18
0
int main(int ac, char **av)
{
	const char * const fifoname = "./fio.fifo";
	const char * const filename = "./fio.file";
	const mode_t mode = S_IRUSR | S_IWUSR | S_IWGRP | S_IWOTH;
	FILE *file;
	char line[BUFSIZ];
	const int lock = 1;
	int errors = 0;
	int fd, wfd;

	if (ac == 2 && !strcmp(av[1], "help"))
	{
		printf("usage: %s\n", *av);
		return EXIT_SUCCESS;
	}

	printf("Testing: %s\n", "fio");

	umask(0);

	if ((fd = fifo_open(fifoname, mode, lock, &wfd)) == -1)
	{
		++errors, printf("Test1: fifo_open(\"%s\", %d, %d) failed (%s)\n", fifoname, (int)mode, lock, strerror(errno));
#ifndef HAVE_FCNTL_THAT_CAN_LOCK_FIFOS
		printf("\n      Can your system lock fifos?\n\n");
#endif
	}
	else
	{
		if ((fcntl_lock(fd, F_SETLK, F_WRLCK, SEEK_SET, 0, 0)) != -1)
			++errors, printf("Test2: fcntl_lock(wrlock) failed\n");

		/* Should really test that the following non-blocking changes do occur */

		if (nonblock_on(fd) == -1)
			++errors, printf("Test3: nonblock_on() failed (%s)\n", strerror(errno));

		if (nonblock_off(fd) == -1)
			++errors, printf("Test4: nonblock_off() failed (%s)\n", strerror(errno));

		if (fcntl_set_flag(fd, O_NONBLOCK) == -1)
			++errors, printf("Test5: fcntl_set_flag() failed (%s)\n", strerror(errno));

		if (fcntl_clear_flag(fd, O_NONBLOCK) == -1)
			++errors, printf("Test6: fcntl_clear_flag() failed (%s)\n", strerror(errno));

		close(fd);
		close(wfd);
		unlink(fifoname);
	}

#define CHECK_FGETLINE(i, size, expected) \
	if ((expected) && !fgetline(line, (size), file)) \
		++errors, printf("Test%d: fgetline() failed\n", (i)); \
	else if ((expected) && strcmp(line, ((expected) ? (expected) : ""))) \
		++errors, printf("Test%d: fgetline() read \"%s\", not \"%s\"\n", (i), line, (expected ? expected : "(null)"));

#define TEST_FGETLINE(i, buf, size, contents, line1, line2, line3) \
	if (!(file = fopen(filename, "wb"))) \
		++errors, printf("Test%d: failed to run test: failed to create test file\n", (i)); \
	else \
	{ \
		if (fwrite((contents), 1, strlen(contents), file) != strlen(contents)) \
			++errors, printf("Test%d: failed to run test: failed to write to test file\n", (i)); \
		else \
		{ \
			fclose(file); \
			if (!(file = fopen(filename, "r"))) \
				++errors, printf("Test%d: failed to run test: failed to open test file for reading\n", (i)); \
			else \
			{ \
				CHECK_FGETLINE((i), (size), (line1)) \
				CHECK_FGETLINE((i), (size), (line2)) \
				CHECK_FGETLINE((i), (size), (line3)) \
				if (fgetline(buf, BUFSIZ, file)) \
					++errors, printf("Test%d: fgetline() failed to return NULL at end of file\n", (i)); \
			} \
		} \
		fclose(file); \
		unlink(filename); \
	}

	TEST_FGETLINE(7, line, BUFSIZ, "abc\ndef\r\nghi\r", "abc\n", "def\n", "ghi\n")
	TEST_FGETLINE(8, line, BUFSIZ, "abc\rdef\nghi\r\n", "abc\n", "def\n", "ghi\n")
	TEST_FGETLINE(9, line, BUFSIZ, "abc\r\ndef\rghi\n", "abc\n", "def\n", "ghi\n")
	TEST_FGETLINE(10, line, BUFSIZ, "abc\ndef\rghi", "abc\n", "def\n", "ghi")
	TEST_FGETLINE(11, line, BUFSIZ, "", (char *)NULL, (char *)NULL, (char *)NULL)
	TEST_FGETLINE(12, line, 5, "abc", "abc", (char *)NULL, (char *)NULL)
	TEST_FGETLINE(13, line, 5, "abc\n", "abc\n", (char *)NULL, (char *)NULL)
	TEST_FGETLINE(14, line, 5, "abc\r\n", "abc\n", (char *)NULL, (char *)NULL)
	TEST_FGETLINE(15, line, 5, "abc\r", "abc\n", (char *)NULL, (char *)NULL)
	TEST_FGETLINE(16, line, 3, "abc\r", "ab", "c\n", (char *)NULL)
	TEST_FGETLINE(17, NULL, 0, "abc\r", (char *)NULL, (char *)NULL, (char *)NULL)

	/* Test read_timeout() and write_timeout() */

	if ((fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_NONBLOCK, S_IRUSR | S_IWUSR)) == -1)
		++errors, printf("Test19: failed to create %s (%s)\n", filename, strerror(errno));
	else
	{
		char buf[12] = "0123456789\n";

		if (write_timeout(fd, 1, 0) == -1)
			++errors, printf("Test18: write_timeout(fd, 1, 0) failed (%s)\n", strerror(errno));
		else if (write(fd, buf, 11) != 11)
			++errors, printf("Test18: write(fd, \"0123456789\\n\", 11) failed (%s)\n", strerror(errno));
		else
		{
			close(fd);

			if ((fd = open(filename, O_RDONLY | O_NONBLOCK)) == -1)
				++errors, printf("Test19: failed to open %s for reading (%s)\n", filename, strerror(errno));
			else if (read_timeout(fd, 1, 0) == -1)
				++errors, printf("Test19: read_timeout(fd, 1, 0) failed (%s)\n", strerror(errno));
			else if (read(fd, buf, 11) != 11)
				++errors, printf("Test19: read(fd) failed (%s)\n", strerror(errno));
		}

		close(fd);
	}

	unlink(filename);

	/* Test error handling */

#define TEST_ERR(i, func) \
	if ((func) != -1) \
		++errors, printf("Test%d: %s failed to return -1\n", (i), (#func)); \
	else if (errno != EINVAL) \
		++errors, printf("Test%d: %s failed (errno = %s, not %s)\n", (i), (#func), strerror(errno), strerror(EINVAL));

	TEST_ERR(20, read_timeout(-1, 0, 0))
	TEST_ERR(21, read_timeout(0, -1, 0))
	TEST_ERR(22, read_timeout(0, 0, -1))
	TEST_ERR(23, write_timeout(-1, 0, 0))
	TEST_ERR(24, write_timeout(0, -1, 0))
	TEST_ERR(25, write_timeout(0, 0, -1))
	TEST_ERR(26, rw_timeout(-1, 0, 0))
	TEST_ERR(27, rw_timeout(0, -1, 0))
	TEST_ERR(28, rw_timeout(0, 0, -1))
	TEST_ERR(29, nap(-1, 0))
	TEST_ERR(30, nap(0, -1))

	if (errors)
		printf("%d/30 tests failed\n", errors);
	else
		printf("All tests passed\n");

#ifndef HAVE_FCNTL_THAT_CAN_LOCK_FIFOS
	printf("\n");
	printf("    Note: Some systems (e.g. FreeBSD) can't lock fifos so fifo_open()\n");
	printf("    can't guarantee a unique reader.\n");
#endif

	return (errors == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}