• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ perror函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中perror函数的典型用法代码示例。如果您正苦于以下问题:C++ perror函数的具体用法?C++ perror怎么用?C++ perror使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了perror函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: main

int main(int argc, char *argv[]) {
	int rc;
	pid_t pid;
	int waitstatus;
	int filedes[2];
	int c, o;
	char buf[BUFSIZ];
	unsigned long magic_token = SD_ID_MAGIC+1;
	int manual = 0;
	int exit_hat = 0;
	char * manual_string;

	while ((c = getopt_long (argc, argv, "+", long_options, &o)) != -1) {
		if (c == 0) {
			switch (o) {
			    case 0: 
			    	magic_token = strtoul (optarg, NULL, 10);
				break;
			    case 1:
			    	manual = 1;
				manual_string = 
					(char *) malloc(strlen(optarg) + 1);
				if (!manual_string) {
					fprintf(stderr, "FAIL: malloc failed\n");
					exit(1);
				}
				strcpy(manual_string, optarg);
				break;
			    case 2:
			    	exit_hat = 1;
				break;
			    case 3:
			        usage(argv[0]);
				break;
			    default:
			        usage(argv[0]);
				break;
			}
		} else {
			usage(argv[0]);
		}
	}

	if (!argv[optind])
		usage(argv[0]);

	rc = pipe(filedes);
	if (rc != 0) {
		perror("FAIL: pipe failed");
		exit(1);
	}
	
	pid = fork();
	if (pid == -1) {
		fprintf(stderr, "FAIL: fork failed - %s\n",
			strerror(errno));
		exit(1);
	} else if (pid != 0) {
		/* parent */
		close(filedes[1]);
		read(filedes[0], &buf, sizeof(buf));
		rc = wait(&waitstatus);
		if (rc == -1){
			fprintf(stderr, "FAIL: wait failed - %s\n",
				strerror(errno));
			exit(1);
		}
	} else {
		/* child */
		char * pname = malloc (strlen(argv[optind]) + 3);
		if (!pname) {
			perror ("FAIL: child malloc");
			return -1;
		}
		sprintf (pname, "%s", argv[optind]);
		
		rc = !manual ? change_hat(argv[optind], magic_token) 
			     : manual_change_hat(argv[optind], manual_string); 
		if (rc != 0) {
			rc = !manual ? change_hat(NULL, magic_token) 
				     : manual_change_hat(NULL, manual_string); 
			fprintf(stderr, "FAIL: hat for %s does not exist\n",
				argv[optind]);
			exit(1);
		}		

		close(filedes[0]);
		fclose(stdout);
		rc = dup2(filedes[1], STDOUT_FILENO);
		if (rc < 0) {
			perror("FAIL: pipe failed");
			exit(1);
		}

		exit(execv(pname, &argv[optind]));
	}

	if (exit_hat) {
		rc = !manual ? change_hat(NULL, magic_token) 
			     : manual_change_hat(NULL, manual_string); 
//.........这里部分代码省略.........
开发者ID:crossbuild,项目名称:apparmor,代码行数:101,代码来源:changehat_wrapper.c


示例2: err_exit

void err_exit(char *message)
 {
  perror(message);
  exit(1);
 }
开发者ID:debind,项目名称:netsend,代码行数:5,代码来源:netrecvUDP.c


示例3: netconf_get_fw

/*
 * Get a list of the current firewall entries
 * @param	fw_list	list of firewall entries
 * @return	0 on success and errno on failure
 */
int
netconf_get_fw(netconf_fw_t *fw_list)
{
	const char **table;
	const char *chain;
	const struct ipt_entry *entry;
	struct iptc_handle *handle = NULL;

	/* Initialize list */
	netconf_list_init(fw_list);

	/* Search all default tables */
	for (table = &netconf_table_names[0]; *table; table++) {

		if (strcmp(*table, "filter") && strcmp(*table, "nat"))
			continue;		

		if (!(handle = iptc_init(*table))) {
			fprintf(stderr, "%s\n", iptc_strerror(errno));
			goto err;
		}

		/* Search all default chains */
		for (chain = iptc_first_chain(handle); chain; chain = iptc_next_chain(handle)) {

			if (strcmp(chain, "INPUT") && strcmp(chain, "FORWARD") && strcmp(chain, "OUTPUT") &&
			    strcmp(chain, "PREROUTING") && strcmp(chain, "POSTROUTING") &&
			    strcmp(chain, "VSERVER") && strcmp(chain, "UPNP"))
				continue;

			/* Search all entries */
			for (entry = iptc_first_rule(chain, handle); entry; entry = iptc_next_rule(entry, handle)) {
				int num = target_num(entry, handle);
				netconf_fw_t *fw = NULL;
				netconf_filter_t *filter = NULL;
				netconf_nat_t *nat = NULL;
				netconf_app_t *app = NULL;

				const struct ipt_entry_match *match;
				const struct ipt_entry_target *target;
				struct ipt_mac_info *mac = NULL;
				struct ipt_state_info *state = NULL;
				struct ipt_conntrack_info *conntrack = NULL;
				struct ipt_time_info *time = NULL;

				/* Only know about TCP/UDP */
				if (!netconf_valid_ipproto(entry->ip.proto))
					continue;

				/* Only know about target types in the specified tables */
				if (!netconf_valid_target(num) || (netconf_table_name[num] &&
				    strncmp(netconf_table_name[num], *table, IPT_FUNCTION_MAXNAMELEN) != 0))
					continue;

				/* Only know about specified target types */
				if (netconf_valid_filter(num))
					fw = (netconf_fw_t *) (filter = calloc(1, sizeof(netconf_filter_t)));
				else if (netconf_valid_nat(num))
					fw = (netconf_fw_t *) (nat = calloc(1, sizeof(netconf_nat_t)));
				else if (num == NETCONF_APP)
					fw = (netconf_fw_t *) (app = calloc(1, sizeof(netconf_app_t)));
				else
					continue;

				if (!fw) {
					perror("calloc");
					goto err;
				}
				netconf_list_add(fw, fw_list);

				/* Get IP addresses */
				fw->match.src.ipaddr.s_addr = entry->ip.src.s_addr;
				fw->match.src.netmask.s_addr = entry->ip.smsk.s_addr;
				fw->match.dst.ipaddr.s_addr = entry->ip.dst.s_addr;
				fw->match.dst.netmask.s_addr = entry->ip.dmsk.s_addr;
				fw->match.flags |= (entry->ip.invflags & IPT_INV_SRCIP) ? NETCONF_INV_SRCIP : 0;
				fw->match.flags |= (entry->ip.invflags & IPT_INV_DSTIP) ? NETCONF_INV_DSTIP : 0;

				/* Get interface names */
				strncpy(fw->match.in.name, entry->ip.iniface, IFNAMSIZ);
				strncpy(fw->match.out.name, entry->ip.outiface, IFNAMSIZ);
				fw->match.flags |= (entry->ip.invflags & IPT_INV_VIA_IN) ? NETCONF_INV_IN : 0;
				fw->match.flags |= (entry->ip.invflags & IPT_INV_VIA_OUT) ? NETCONF_INV_OUT : 0;

				fw->match.ipproto = entry->ip.proto;

				/* Get TCP port(s) */
				if (entry->ip.proto == IPPROTO_TCP) {
					struct ipt_tcp *tcp = NULL;

					for_each_ipt_match(match, entry) {
						if (strncmp(match->u.user.name, "tcp", IPT_FUNCTION_MAXNAMELEN) != 0)
							continue;

						tcp = (struct ipt_tcp *) &match->data[0];
//.........这里部分代码省略.........
开发者ID:BackupGGCode,项目名称:wl500g,代码行数:101,代码来源:netconf_linux.c


示例4: diep

void diep(char *s)
{
  perror(s);
  exit(1);
}
开发者ID:joseparnau,项目名称:rosjac,代码行数:5,代码来源:phantom_udp_client.cpp


示例5: sendFile

void sendFile(char *serverName, unsigned int serverPort, char *filePath)
{
    struct sockaddr_in serverAddress;

    if ((clientSocketDescriptor =
         createTcpSocket(serverName, serverPort, &serverAddress)) == -1) {
        fprintf(stderr, "Creation socket error\n");
        exit(EXIT_FAILURE);
    }

    if (connect
        (clientSocketDescriptor, (struct sockaddr *) &serverAddress,
         sizeof(serverAddress)) < 0) {
        perror("connect");
        exit(EXIT_FAILURE);
    }

    FILE *file = fopen(filePath, "r+");
    if (file == NULL) {
        perror("Open file error");
        exit(EXIT_FAILURE);
    }

    long fileSize = GetFileSize(file);

    char replyBuf[replyBufSize];
    sprintf(replyBuf, "%s:%ld", basename(filePath), fileSize);

    // Send file name and file size
    if (send(clientSocketDescriptor, replyBuf, sizeof(replyBuf), 0) == -1) {
        perror("Send error");
        exit(EXIT_FAILURE);
    }

    char buf[bufSize];
    long totalBytesSent = 0;
    size_t bytesRead;

    int middle = (fileSize / bufSize) / 2;
    if (middle == 0)
        middle = 1;

    // Sending file
    printf("Start sending file.\n");
    int i = 0;
    while (totalBytesSent < fileSize) {
        bytesRead = fread(buf, 1, sizeof(buf), file);
        int sendBytes = send(clientSocketDescriptor, buf, bytesRead, 0);
        if (sendBytes < 0) {
            perror("Sending error\n");
            exit(EXIT_FAILURE);
        }
        totalBytesSent += sendBytes;

        // Send OOB data in the middle of sending file
        if (++i == middle) {
            printf("Sent OOB byte. Total bytes sent: %ld\n",
                   totalBytesSent);
            sendBytes = send(clientSocketDescriptor, "!", 1, MSG_OOB);
            if (sendBytes < 0) {
                perror("Sending error");
                exit(EXIT_FAILURE);
            }
        }
    }
    printf("Sending file completed. Total bytes sent: %ld\n",
           totalBytesSent);
    close(clientSocketDescriptor);
    fclose(file);
}
开发者ID:56Nexus,项目名称:Lab4,代码行数:70,代码来源:main.c


示例6: OpenComport

int OpenComport(int comport_number, int baudrate)
{
    int baudr;

    if((comport_number>21)||(comport_number<0))
    {
        printf("illegal comport number\n");
        return(1);
    }

    switch(baudrate)
    {
    case      50 :
        baudr = B50;
        break;
    case      75 :
        baudr = B75;
        break;
    case     110 :
        baudr = B110;
        break;
    case     134 :
        baudr = B134;
        break;
    case     150 :
        baudr = B150;
        break;
    case     200 :
        baudr = B200;
        break;
    case     300 :
        baudr = B300;
        break;
    case     600 :
        baudr = B600;
        break;
    case    1200 :
        baudr = B1200;
        break;
    case    1800 :
        baudr = B1800;
        break;
    case    2400 :
        baudr = B2400;
        break;
    case    4800 :
        baudr = B4800;
        break;
    case    9600 :
        baudr = B9600;
        break;
    case   19200 :
        baudr = B19200;
        break;
    case   38400 :
        baudr = B38400;
        break;
    case   57600 :
        baudr = B57600;
        break;
    case  115200 :
        baudr = B115200;
        break;
    case  230400 :
        baudr = B230400;
        break;
    case  460800 :
        baudr = B460800;
        break;
    case  500000 :
        baudr = B500000;
        break;
    case  576000 :
        baudr = B576000;
        break;
    case  921600 :
        baudr = B921600;
        break;
    case 1000000 :
        baudr = B1000000;
        break;
    default      :
        printf("invalid baudrate\n");
        return(1);
        break;
    }

    Cport[comport_number] = open(comports[comport_number], O_RDWR | O_NOCTTY | O_NDELAY);
    if(Cport[comport_number]==-1)
    {
        perror("unable to open comport ");
        return(1);
    }

    error = tcgetattr(Cport[comport_number], old_port_settings + comport_number);
    if(error==-1)
    {
        close(Cport[comport_number]);
        perror("unable to read portsettings ");
        return(1);
//.........这里部分代码省略.........
开发者ID:microdevicer,项目名称:meteoboard-project,代码行数:101,代码来源:rs232.c


示例7: LocalFilesRecursiveDir

int LocalFilesRecursiveDir (
	struct collectionFormat *collection,
        int (*documentExist)(struct collectionFormat *collection,struct crawldocumentExistFormat *crawldocumentExist),
        int (*documentAdd)(struct collectionFormat *collection,struct crawldocumentAddFormat *crawldocumentAdd),
	char prefix[],
	char dirname[],
	int accessmode ) {


	//char *dokument_buff = malloc(_dokument_buff_size +1);
	char *dokument_buff;

	printf("opening dir \"%s\", prefix %s\n",dirname,prefix);

	DIR *DIRH;
	struct dirent *dp;
	char nextdirname[512];
	char filname[512];
	char lotinternfilname[512];
	FILE *FH;
	struct stat inode;      // lager en struktur for fstat å returnere.
	int dokument_size;
	int diraccessmode;
	int filecessmode;
	struct passwd *pw;
	struct group  *gp;
	//char acl[4][64];
	char acl[3 * 64];
	int count;
	char uri[512];

	struct crawldocumentExistFormat crawldocumentExist;
        struct crawldocumentAddFormat crawldocumentAdd;

	if (stat(dirname,&inode) != 0) {
		perror("stat");
		return 0;
	}
	//har ownaccessmode som den laveste i hele pathen
	int ownaccessmode = inode.st_mode & accessmode;
	
	if ((DIRH = opendir(dirname)) == NULL) {
		perror(dirname);	
		return;
	}	
	
	while ((dp = readdir(DIRH)) != NULL) {

		sprintf(nextdirname,"%s/%s",dirname,dp->d_name);

		if (stat(nextdirname,&inode) != 0) {
			perror("fstat");
			continue;
		}


		if (dp->d_name[0] == '.') {
			printf(". domain (\"%s\")\n",dp->d_name);
		}
		//else if (dp->d_type == DT_DIR) {
		else if (S_ISDIR(inode.st_mode)) {

			sprintf(nextdirname,"%s/%s",dirname,dp->d_name);
			printf("dir (nextdirname %s)\n",nextdirname);

			//kaller seg selv rekurift
			LocalFilesRecursiveDir(collection,documentExist,documentAdd,prefix,nextdirname,ownaccessmode);
		}
		//else if (dp->d_type == DT_REG) {
		else if (S_ISREG(inode.st_mode)) {
			sprintf(filname,"%s/%s",dirname,dp->d_name);
			snprintf(uri,sizeof(uri),"%s/%s",prefix,filname);
			//sprintf(lotinternfilname,"%s%s",lotinternpath,dp->d_name);
			printf("file %s\n",filname);	

			//rSendFile(filname,lotinternfilname,lotNr, "w",subname);
			if ((FH = fopen(filname,"rb")) == NULL) {
				perror(filname);
				//exit(1);
				continue;
			}
			


			crawldocumentExist.documenturi = uri;
                        crawldocumentExist.lastmodified = inode.st_mtime;
                        crawldocumentExist.dokument_size = inode.st_size;


			//spør Boitho om filområdet finnes
			//if (!(documentExist)(collection, &crawldocumentExist ) ) {
				dokument_size = inode.st_size;
				dokument_buff = malloc(dokument_size +1);

				printf("uid %i, gid %i\n",inode.st_uid,inode.st_gid);
				//lager acl
				acl[0] = '\0';
				filecessmode = ownaccessmode & inode.st_mode;
				printf("mode %i\n",(int)inode.st_mode);
				if (filecessmode & S_IRUSR) {
//.........这里部分代码省略.........
开发者ID:lgsonic,项目名称:enterprise-search,代码行数:101,代码来源:crawlLocalFiles.c


示例8: main

int
main(int argc, char *argv[])
{
	pid_t 	pid;
	int		status;
  int   ServerFD[2];
  int   ServerFD2[2];
  char  *data = "accept";
  char  *data2 = "reject";
  char  *terminate = "terminate";
  char  pubbuf[1025];
  char  pubbufend[1025];
  char  pubbufterm[1025];
  char  subbuf[1025];
  char  subbufend[1025];
  char  subbufterm[1025];

  pipe(ServerFD);
  pipe(ServerFD2);
	pid = fork();

	if(pid == 0){//this is the child of the main process, the DIServer
    int i;
		//n is # of publisher
		int n = atoi(argv[1]);
		//m is number of subscribers
		int m = atoi(argv[2]);
    //t are topics	
    int t = atoi(argv[3]);
    pthread_t pubthreads[n];
    pthread_t subthreads[m];
    int   rc;
    int   rc2;
    void  *pubthreadstatus;
    void  *subthreadstatus;

    pthread_attr_t pubattr;
    pthread_attr_t subattr;

    pthread_attr_init(&pubattr);
    pthread_attr_setdetachstate(&pubattr, PTHREAD_CREATE_JOINABLE);

    pthread_attr_init(&subattr);
    pthread_attr_setdetachstate(&subattr, PTHREAD_CREATE_JOINABLE);

    pthread_mutex_init(&mutexlock,NULL);


    Record record[n+m];
		/*need to use n and m to create child procs of the 
		DIServer, publishers and subscriers*/
		//loop to create publisher procs and stroe pid in array;
		pid_t pubpid;
		pid_t subpid;

		//map space for the pub array
		pubpids = mmap(0, MAX_PIDS*sizeof(pid_t), PROT_READ|PROT_WRITE,
              MAP_SHARED | MAP_ANONYMOUS, -1, 0);
		 if (!pubpids) {
    		perror("mmap failed");
    		exit(1);
 		 }
  		memset((void *)pubpids, 0, MAX_PIDS*sizeof(pid_t)); 		 
 		 //map space for sub array
		subpids = mmap(0, MAX_PIDS*sizeof(pid_t), PROT_READ|PROT_WRITE,
              MAP_SHARED | MAP_ANONYMOUS, -1, 0);
		 if (!subpids) {
    		perror("mmap failed");
    		exit(1);
 		 }
  		memset((void *)subpids, 0, MAX_PIDS*sizeof(pid_t));

  		//loop to creat forked pubs
  		for(i=0;i<n;i++)
  		{
        //create the record struct
        //create the publisher struct
        int z;
        Publisher pub;
        pub.pubConnect = "Pub Connect";
        pub.pubTopic = "Topic 1";//topic of interest
        pub.pubEnd = "End";
        pub.pubterm = "terminate";
        pipe(pub.fileDescriptor);
  			pubpid = fork();
        int articles;
        char article[12];
  			if(pubpid == 0)
  			{
          //doPublisher(n);
          write(pub.fileDescriptor[1], pub.pubConnect, strlen(pub.pubConnect));
          if ((z = read(ServerFD[0], pubbuf, 1024)) >= 0) {
              pubbuf[z] = 0; /* terminate the string */ 
              //printf("pub read %d bytes from the DIServer pipe: \"%s\"\n", z, pubbuf);
              if (strcmp(pubbuf, data) == 0)
              {
                write(pub.fileDescriptor[1], pub.pubTopic, strlen(pub.pubTopic));
                if ((z = read(ServerFD[0], pubbufend, 1024)) >= 0) {
                  pubbufend[z] = 0;
                  //printf("pub read %d bytes from the DIServer pipe: \"%s\"\n", z, pubbufend);
//.........这里部分代码省略.........
开发者ID:mmaurice,项目名称:UOProjects,代码行数:101,代码来源:DIServer.c


示例9: main

int main(int argc, char *argv[])
{	
	if (getpid() == 1)
	{
		if (open("/dev/tty0", O_RDWR) != 0) return 1;
		if (dup(0) != 1) return 1;
		if (dup(1) != 2) return 1;
		
		setenv("PATH", "/usr/local/bin:/usr/bin:/bin", 1);
		setenv("HOME", "/root", 1);
		setenv("LD_LIBRARY_PATH", "/usr/local/lib:/usr/lib:/lib", 1);

		struct sigaction sa;
		memset(&sa, 0, sizeof(struct sigaction));
		sa.sa_sigaction = on_signal;
		sigemptyset(&sa.sa_mask);
		sa.sa_flags = SA_SIGINFO;
		if (sigaction(SIGINT, &sa, NULL) != 0)
		{
			perror("sigaction SIGINT");
			return 1;
		};
		if (sigaction(SIGCHLD, &sa, NULL) != 0)
		{
			perror("sigaction SIGCHLD");
			return 1;
		};
		if (sigaction(SIGTERM, &sa, NULL) != 0)
		{
			perror("sigaction SIGTERM");
			return 1;
		};
		if (sigaction(SIGHUP, &sa, NULL) != 0)			// SIGHUP is sent when the power button is pressed
		{
			perror("sigaction SIGHUP");
			return 1;
		};
		
		if (mkdir("/sem", 01777) != 0)
		{
			perror("mkdir /run/sem");
			return 1;
		};
		
		loadmods();
		
		printf("init: initializing partitions...\n");
		init_parts();
		
		printf("init: looking for root filesystem...\n");
		if (try_mount_root() != 0)
		{
			printf("init: failed to find the root filesystem!\n");
			return 1;
		};
		
		printf("init: setting up second-level filesystem...\n");
		if (mount("bind", "/dev", "/rootfs/dev", 0, NULL, 0) != 0)
		{
			perror("init: bind /dev");
			return 1;
		};

		if (mount("bind", "/proc", "/rootfs/proc", 0, NULL, 0) != 0)
		{
			perror("init: bind /proc");
			return 1;
		};

		if (mount("bind", "/initrd", "/rootfs/initrd", 0, NULL, 0) != 0)
		{
			perror("init: bind /initrd");
			return 1;
		};

		if (mount("bind", "/run", "/rootfs/run", 0, NULL, 0) != 0)
		{
			perror("init: bind /run");
			return 1;
		};

		if (mount("bind", "/run", "/rootfs/var/run", 0, NULL, 0) != 0)
		{
			perror("init: bind /var/run");
			return 1;
		};

		printf("init: setting up fsinfo...\n");
		int fd = open("/run/fsinfo", O_WRONLY | O_CREAT | O_EXCL, 0644);
		if (fd == -1)
		{
			perror("init: open /run/fsinfo");
			return 1;
		};
		
		struct __fsinfo_record record;
		memset(&record, 0, sizeof(struct __fsinfo_record));
		strcpy(record.__image, rootImage);
		strcpy(record.__mntpoint, "/");
		write(fd, &record, sizeof(struct __fsinfo_record));
//.........这里部分代码省略.........
开发者ID:madd-games,项目名称:glidix,代码行数:101,代码来源:init.c


示例10: main

int main(int argc, char** argv)
{
	mqd_t msg_queue = mq_open("/CprE308-Queue", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP, NULL);
	if(msg_queue == -1)
	{
		perror("mq_open\n");
		return -1;
	}

	// Determine max. msg size; allocate buffer to receive msg
	struct mq_attr attr;
	char *buf;
	if (mq_getattr(msg_queue, &attr))
	{
		perror("mq_getattr\n");
		exit(-1);
	}
	buf = malloc(attr.mq_msgsize);
	if (buf == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	
	sleep(10);
	
	ssize_t size;
	size = mq_receive(msg_queue, buf, attr.mq_msgsize, NULL);
	if (size == -1)
	{
		perror("mq_receive\n");
		exit(-1);
	}
	printf("Received message \"%s\"\n", buf);
	
	
	size = mq_receive(msg_queue, buf, attr.mq_msgsize, NULL);
	if (size == -1)
	{
		perror("mq_receive\n");
		exit(-1);
	}
	printf("Received message \"%s\"\n", buf);
	
	
	free(buf);
	
	char my_string[] = "I am Clara";
	
	if( mq_send(msg_queue, my_string, strlen(my_string), 12))
	{
		perror("mq_send\n");
		return -1;
	}

	char my_string2[] = "I am Rose";
	
	if( mq_send(msg_queue, my_string2, strlen(my_string2), 11))
	{
		perror("mq_send\n");
		return -1;
	}
	return 0;
}
开发者ID:leerob,项目名称:CprE308_Labs,代码行数:64,代码来源:mq_test2.c


示例11: lock_cachefile

static void lock_cachefile(int type)
{
	struct flock fl = {
		.l_len = 0,
		.l_start = 0,
		.l_whence = SEEK_SET,
	};

	fl.l_pid = getpid();
	fl.l_type = type;

	if (verbose)
		output(2, "waiting on lock for cachefile\n");

	if (fcntl(cachefile, F_SETLKW, &fl) == -1) {
		perror("fcntl F_SETLKW");
		return;
	}

	if (verbose)
		output(2, "took lock for cachefile\n");
}

static void unlock_cachefile(void)
{
	struct flock fl = {
		.l_len = 0,
		.l_start = 0,
		.l_whence = SEEK_SET,
	};

	fl.l_pid = getpid();
	fl.l_type = F_UNLCK;

	if (fcntl(cachefile, F_SETLK, &fl) == -1) {
		perror("fcntl F_UNLCK F_SETLK ");
		return;
	}

	if (verbose)
		output(2, "dropped lock for cachefile\n");
}

static unsigned int valid_proto(unsigned int family)
{
	const char *famstr;

	famstr = get_domain_name(family);

	/* Not used for creating sockets. */
	if (strncmp(famstr, "UNSPEC", 9) == 0)
		return FALSE;
	if (strncmp(famstr, "BRIDGE", 9) == 0)
		return FALSE;
	if (strncmp(famstr, "SECURITY", 11) == 0)
		return FALSE;

	/* Not actually implemented (or now removed). */
	if (strncmp(famstr, "NETBEUI", 10) == 0)
		return FALSE;
	if (strncmp(famstr, "ASH", 6) == 0)
		return FALSE;
	if (strncmp(famstr, "ECONET", 9) == 0)
		return FALSE;
	if (strncmp(famstr, "SNA", 6) == 0)
		return FALSE;
	if (strncmp(famstr, "WANPIPE", 10) == 0)
		return FALSE;

	/* Needs root. */
	if (orig_uid != 0) {
		if (strncmp(famstr, "KEY", 6) == 0)
			return FALSE;
		if (strncmp(famstr, "PACKET", 9) == 0)
			return FALSE;
		if (strncmp(famstr, "LLC", 6) == 0)
			return FALSE;
	}

	return TRUE;
}

static bool write_socket_to_cache(struct socket_triplet *st)
{
	unsigned int buffer[3];
	int n;

	if (cachefile == -1)
		return FALSE;

	buffer[0] = st->family;
	buffer[1] = st->type;
	buffer[2] = st->protocol;
	n = write(cachefile, &buffer, sizeof(int) * 3);
	if (n == -1) {
		outputerr("something went wrong writing the cachefile! : %s\n", strerror(errno));
		return FALSE;
	}
	return TRUE;
}
//.........这里部分代码省略.........
开发者ID:kernelslacker,项目名称:trinity,代码行数:101,代码来源:sockets.c


示例12: slam_junk

void*
slam_junk(void *data)
{
	int fd, fd_rand;
	int pages, bytes_wrote, ret;
	char fname[100];
	char buff[4096];

	gen_random_filename(fname, sizeof(fname));
	pthread_cleanup_push(slam_cleanup, fname);
	while(1)
	{
		// O_SYNC tried
		fd = open(fname, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU | S_IRWXO);
		if(fd < 0)
		{
			printf("open:%s:\n",fname);
			perror("open:");
			pthread_exit(NULL);
		}
		fd_rand = open("/dev/zero", O_RDONLY);
		if(fd_rand < 0)
		{
			perror("open:/dev/zero:");
			close(fd);
			pthread_exit(NULL);
		}
		//pages = random()%max_pages + 1;
		pages = max_pages;
		bytes_wrote = 0;
		while(pages--)
		{
			if((ret = read(fd_rand, buff, sizeof(buff)))<0)
			{	
				perror("read:");
				close(fd_rand);
				close(fd);
				pthread_exit(NULL);
			}
			if((ret = write(fd, buff, ret))<0)
			{
				perror("write:");
				close(fd_rand);
				close(fd);
				pthread_exit(NULL);
				
			}
			bytes_wrote+=ret;
			total_bytes_written += bytes_wrote;
		}
		
		//lets see..whether it hangs
		fsync(fd);
		close(fd);
		close(fd_rand);

		fd = open(fname, O_RDONLY);
		while(read(fd, buff, sizeof(buff)));
		close(fd);

		//printf("%d bytes written\n", bytes_wrote);
		//pthread_mutex_lock(&total_bytes_mutex);
		//pthread_mutex_unlock(&total_bytes_mutex);		

			
		pthread_testcancel();
	}
	pthread_cleanup_pop(0);
	pthread_exit(NULL);
}
开发者ID:fredrickprashanth,项目名称:sugarnspice,代码行数:70,代码来源:fs_slammer.c


示例13: main

int 
main(int argc, char *argv[])
{
	int ret;
	int i;

	if(argc < 6)
	{
		printf("Usage: fs_slammer <hddisk> <dir> <no. of files> <no-of-pages> <time in secs> <rw>\n");
		return -1;
	}
	
	time_t tt;
	time(&tt);
	srandom(tt);

	char fs_path[256];
	char *hd_name;
	struct stat stat_buf;
	char **argp =++argv;

	hd_name = (char *)malloc(10);
	strcpy(hd_name, *argp++);
	if((ret = stat(hd_name, &stat_buf))<0)
	{
		perror("stat:");
		return ret;
	}
	
	strcpy(fs_path, *argp++);
	if((ret = stat(fs_path, &stat_buf))<0)
	{
		perror("stat:");
		return ret;
	}
	
	if((ret=chdir(fs_path))<0)
	{
		printf("%s:\n", fs_path);
		perror("chdir:");
		return ret;
	}
	
	int no_threads = 0;

	sscanf(*argp++, "%d", &no_threads);

	sscanf(*argp++, "%d", &max_pages);

	int slam_time;
	sscanf(*argp++, "%d", &slam_time);

	char rw[4];
	sscanf(*argp++, "%s", rw);

	pthread_t *read_threads;
	pthread_t *slam_threads;

	if(strchr(rw, 'w'))
	{
		slam_threads = (pthread_t*)malloc(sizeof(pthread_t)*no_threads);

		pthread_attr_t attr;
		pthread_attr_init(&attr);
		pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);


		for(i = 0; i < no_threads; i++)
		{
			if((ret = pthread_create(slam_threads+i, &attr, slam_junk, NULL)))
			{
				perror("pthread_create:");
				return ret;
			}
		}
	}
	
	if(strchr(rw, 'r'))
	{
		read_threads = (pthread_t*)malloc(sizeof(pthread_t)*no_threads);

		pthread_attr_t attr;
		pthread_attr_init(&attr);
		pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);


		for(i = 0; i < no_threads; i++)
		{
			if((ret = pthread_create(read_threads+i, &attr, raw_reader, hd_name)))
			{
				perror("pthread_create:");
				return ret;
			}
		}
	}
	

	signal(SIGINT, termination_hdlr);
	signal(SIGTERM, termination_hdlr);
	signal(SIGQUIT, termination_hdlr);
//.........这里部分代码省略.........
开发者ID:fredrickprashanth,项目名称:sugarnspice,代码行数:101,代码来源:fs_slammer.c


示例14: setRaw

static void setRaw(int fd,
		    int baud,
		    int databits,
		    char parity,
		    unsigned stopBits,
		    struct termios &oldState)
{
	tcgetattr(fd,&oldState);

	/* set raw mode for keyboard input */
	struct termios newState = oldState;
	newState.c_cc[VMIN] = 1;

	bool nonStandard = false ;
	unsigned baudConst ;
	if (baudRateToConst(baud, baudConst)) {
		cfsetispeed(&newState, baudConst);
		cfsetospeed(&newState, baudConst);
	}
	else {
		cfsetispeed(&newState,B38400);
		cfsetospeed(&newState,B38400);
		bool worked = false ;
		struct serial_struct nuts;
		int rval = ioctl(fd, TIOCGSERIAL, &nuts);
		if (0 == rval) {
			unsigned const divisor = nuts.baud_base / baud ;
			nuts.custom_divisor = divisor ;
			nuts.flags &= ~ASYNC_SPD_MASK;
			nuts.flags |= ASYNC_SPD_CUST;
			rval = ioctl(fd, TIOCSSERIAL, &nuts);
			if (0 == rval) {
				printf("baud changed\n");
				rval = ioctl(fd, TIOCGSERIAL, &nuts);
				if (0 == rval) {
					printf("divisor is now %u\n", nuts.custom_divisor);
				}
				else
					perror("TIOCGSERIAL2");
			}
			else
				perror("TIOCSSERIAL");
		}
		else
			perror("TIOCGSERIAL");
	} // non-standard serial

	//
	// Note that this doesn't appear to work!
	// Reads always seem to be terminated at 16 chars!
	//
	newState.c_cc[VTIME] = 0; // 1/10th's of a second, see http://www.opengroup.org/onlinepubs/007908799/xbd/termios.html

	newState.c_cflag &= ~(PARENB|CSTOPB|CSIZE|CRTSCTS);		 // Mask character size to 8 bits, no parity, Disable hardware flow control

	if ('E' == parity) {
		newState.c_cflag |= PARENB ;
		newState.c_cflag &= ~PARODD ;
	}
	else if ('O' == parity) {
		newState.c_cflag |= PARENB | PARODD ;
	}
	else if ('S' == parity) {
		newState.c_cflag |= PARENB | IGNPAR | CMSPAR ;
		newState.c_cflag &= ~PARODD ;
	}
	else if ('M' == parity) {
		newState.c_cflag |= PARENB | IGNPAR | CMSPAR | PARODD ;
	}
	else {
	} // no parity... already set

	newState.c_cflag |= (CLOCAL | CREAD |CS8);			 // Select 8 data bits
	if (7 == databits) {
		newState.c_cflag &= ~CS8 ;
	}

	if (1 != stopBits)
		newState.c_cflag |= CSTOPB ;

	newState.c_lflag &= ~(ICANON | ECHO);				 // set raw mode for input
	newState.c_iflag &= ~(IXON | IXOFF | IXANY|INLCR|ICRNL|IUCLC);	 //no software flow control
	newState.c_oflag &= ~OPOST;			 //raw output
	tcsetattr(fd, TCSANOW, &newState);
}
开发者ID:LaughingSun,项目名称:nanocomm,代码行数:85,代码来源:nanocomm.cpp


示例15: setup_every_copy

void setup_every_copy()
{
	int i;
	char tmpfilename[256] = "";

	/* Initialize test dir and file names */
	sprintf(pathname, "readlinkattestdir%d", getpid());
	sprintf(dpathname, "dreadlinkattestdir%d", getpid());
	sprintf(testfile, "readlinkattestfile%d.txt", getpid());
	sprintf(dtestfile, "dreadlinkattestfile%d.txt", getpid());
	sprintf(testfile2, "readlinkattestdir%d/readlinkattestfile%d.txt",
		getpid(), getpid());
	sprintf(dtestfile2, "dreadlinkattestdir%d/dreadlinkattestfile%d.txt",
		getpid(), getpid());
	sprintf(testfile3, "/tmp/readlinkattestfile%d.txt", getpid());
	sprintf(dtestfile3, "/tmp/dreadlinkattestfile%d.txt", getpid());

	ret = mkdir(pathname, 0700);
	if (ret < 0) {
		perror("mkdir: ");
		exit(-1);
	}

	ret = mkdir(dpathname, 0700);
	if (ret < 0) {
		perror("mkdir: ");
		exit(-1);
	}

	dirfd = open(dpathname, O_DIRECTORY);
	if (dirfd < 0) {
		perror("open: ");
		exit(-1);
	}

	fd = open(testfile, O_CREAT | O_RDWR, 0600);
	if (fd < 0) {
		perror("open: ");
		exit(-1);
	}

	ret = symlink(testfile, dtestfile);
	if (ret < 0) {
		perror("symlink: ");
		exit(-1);
	}

	fd = open(testfile2, O_CREAT | O_RDWR, 0600);
	if (fd < 0) {
		perror("open: ");
		exit(-1);
	}

	tmpfilename[0] = '\0';
	strcat(strcat(tmpfilename, "../"), testfile2);
	ret = symlink(tmpfilename, dtestfile2);
	if (ret < 0) {
		perror("symlink: ");
		exit(-1);
	}

	fd = open(testfile3, O_CREAT | O_RDWR, 0600);
	if (fd < 0) {
		perror("open: ");
		exit(-1);
	}

	ret = symlink(testfile3, dtestfile3);
	if (ret < 0) {
		perror("symlink: ");
		exit(-1);
	}

	fds[0] = fds[1] = dirfd;
	fds[2] = fd;
	fds[3] = 100;
	fds[4] = AT_FDCWD;

	filenames[0] = filenames[2] = filenames[3] = filenames[4] = dtestfile;
	filenames[1] = dtestfile3;

	for (i = 0; i < TEST_CASES; i++)
		expected_buff[i][0] = '\0';

	strcat(strcat(expected_buff[0], "../"), testfile2);
	strcat(expected_buff[1], testfile3);
	strcat(expected_buff[2], "");
	strcat(expected_buff[3], "");
	strcat(expected_buff[4], testfile);
}
开发者ID:shubmit,项目名称:shub-ltp,代码行数:90,代码来源:readlinkat01.c


示例16: error

void error(char *msg)
{
    perror(msg);
    exit(1);
}
开发者ID:BrotherMaynard,项目名称:randomCodes,代码行数:5,代码来源:server.c


示例17: main

int main(void)
{
	signal(SIGCHLD, SigchldHandler);
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (-1 == sockfd) {
		perror("Socket error:\n");
		return -1;
	}
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(SERVER_PORT);
	addr.sin_addr.s_addr = inet_addr(SERVER_IP);
	int optval = 1;
	if (-1 == setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))) {
		perror("Set socket option error:\n");
	}
	if (-1 == bind(sockfd, (struct sockaddr *)&addr, sizeof(addr))) {
		perror("Bind error:\n");
		return -1;
	}
	if (-1 == listen(sockfd, SOMAXCONN)) {
		perror("Listen error:\n");
		return -1;
	}
	while (1) {
		struct sockaddr_in clientaddr;
		socklen_t socklen = sizeof(clientaddr);
		int connfd = accept(sockfd, (struct sockaddr *)&clientaddr, &socklen);
		pid_t pid = fork();
		if (-1 == pid) {
			perror("Create process error:\n");
			exit(-1);	
		}
		else if (0 == pid) { //child process
			if (-1 == connfd) {
				perror("Accept error:\n");
				return -1;
			}
			printf("child process.\n");
			printf("client address %s.\n", inet_ntoa(clientaddr.sin_addr));
			while (1) {
				char recbuffer[1024] = {0};
				int readlen = read(connfd, recbuffer, sizeof(recbuffer));	
				if (-1 == readlen) {
					if (EINTR == errno) {
						continue;
					}
					//return - 1;
					exit(-1);
				}
				else if (0 == readlen) {
					printf("Client close.\n");
					close(connfd);
					exit(0);
				}
				else {
//					if (recbuffer[0] == 'c') {
//						close(connfd);
//						exit(0);
//					}
					printf("recv %s.\n", recbuffer);
					int writelen = write(connfd, recbuffer, strlen(recbuffer));
					if (-1 == writelen) {
						if (EINTR == errno) {
							continue;
						}
						close(connfd);
						//shutdown(connfd, SHUT_RDWR);
						exit(-1);
					}
					else if (writelen > 0) {
						//TODO something
					}
					else {
					}
					memset(recbuffer, 0, sizeof(recbuffer));
				}
			}
		}
		else if (pid > 0) { //parent process
			close(connfd);
		}
	}
	return 0;
}
开发者ID:MingYueRuYa,项目名称:cprimeprimecode,代码行数:85,代码来源:echoserver.c


示例18: main

    int main(void)
    {
            int status;
            pid_t pid;
			
			// Allocate a shared block.
			share = mmap(0, 
					 4096,
					 PROT_READ | PROT_WRITE,
                     MAP_SHARED | MAP_ANONYMOUS,
                     -1,
                     0);
				
				
            if ((pid = fork()) < 0) {
                    perror("fork");
                    abort();
            }
            else if (pid == 0) {
                    ptrace(PTRACE_TRACEME, 0, NULL, NULL);
                    kill(getpid(), SIGSTOP);
					share[0] = 1;
//                    open("foo.bar", O_WRONLY | O_CREAT);
					
                    _exit(0);
            }
#if 0
            if (waitpid(pid, &status, 0) < 0) {
                    perror("waitpid");
                    abort();
            }

            assert(WIFSTOPPED(status));
            assert(WSTOPSIG(status) == SIGSTOP);

            if (ptrace(PTRACE_SYSCALL, pid, NULL, NULL) < 0) {
                    perror("ptrace(PTRACE_SYSCALL, ...)");
                    ptrace(PTRACE_KILL, pid, NULL, NULL);
                    abort();
            }

            if (waitpid(pid, &status, 0) < 0) {
                    perror("waitpid");
                    ptrace(PTRACE_KILL, pid, NULL, NULL);
                    abort();
            }

            assert(WIFSTOPPED(status));
            assert(WSTOPSIG(status) == SIGTRAP);
#endif
			printf("ORIG_ACCUM %d and ORIG_EAX %d, DR_OFFSET(0) %d DR_OFFSET(1) %d total %d\n",ORIG_ACCUM, ORIG_EAX, DR_OFFSET(0), DR_OFFSET(1), sizeof(struct user)); 
#if 0
			if(ptrace(PTRACE_ATTACH, pid, 0, 0) < 0) {
                    perror("ptrace(PTRACE_ATTACH, ...)" );
                    ptrace(PTRACE_KILL, pid, NULL, NULL);
                    abort();
			}
#endif

            /* Change the system call to something invalid, so it will be denied.
             */
   //         if (ptrace(PTRACE_POKEUSER, pid, ORIG_ACCUM, 0xbadca11) < 0) {
            if (ptrace(PTRACE_POKEUSER, pid, DR_OFFSET(0), share) < 0) {
                    perror("ptrace(PTRACE_POKEUSER, ...)");
                    ptrace(PTRACE_KILL, pid, NULL, NULL);
                    abort();
            }

            /* Let the process continue */
            ptrace(PTRACE_CONT, pid, NULL, NULL);

            waitpid(pid, &status, 0);
 //           assert(WIFEXITED(status));
            exit(WEXITSTATUS(status));
    }
开发者ID:UTSASRG,项目名称:DifferentTries,代码行数:75,代码来源:debug.c


示例19: main

int main(int argc, char **argv)
{
    int sfd = 0, s = 0;
    int efd = 0;
    struct epoll_event event = {};
    struct epoll_event *events = NULL;

    if (argc != 2)
    {
        fprintf(stderr, "usage: %s [port]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    sfd = create_and_bind(argv[1]);
    if (sfd == -1) {abort();}
    fprintf(stdout, "sfd: %d\n", sfd);

    s = make_socket_non_blocking(sfd);
    if (s == -1) {abort();}

    s = listen(sfd, SOMAXCONN);
    if (s == -1)
    {
        perror("listen");
        abort();
    }

    efd = epoll_create(256);
    if (efd == -1)
    {
        perror("epoll_create1");
        abort();
    }

    event.data.fd = sfd;
    event.events = EPOLLIN | EPOLLET;
    s = epoll_ctl(efd, EPOLL_CTL_ADD, sfd, &event);
    if (s == -1)
    {
        perror("epoll_ctl");
        abort();
    }

    //Buffer where events are returned
    events = calloc(MAXEVENTS, sizeof(event));

    fprintf(stdout, "before event loop\n");
    //The event loop
    while (1)
    {
        int n, i;

        n = epoll_wait(efd, events, MAXEVENTS, -1);
        fprintf(stdout, "epoll wait return: %d\n", n);
        for (i=0; i<n; i++)
        {
            fprintf(stdout, "events[%d].data.fd=%d\n", i, events[i].data.fd);
            if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP)
                    || (!(events[i].events & EPOLLIN)))
            {
                //an error has occured on this fd, or the socket is not ready for reading
                fprintf(stderr, "epoll error\n");
                close(events[i].data.fd);
                continue;
            }
            else if (sfd == events[i].data.fd)
            {
                //we have a notification on the listening socket, which means one or more
                //incoming connections
                fprintf(stdout, "sfd == events[i].data.fd\n");
                while (1)
                {
                    struct sockaddr in_addr = {};
                    socklen_t in_len = 0;
                    int infd = 0;
                    char hbuf[NI_MAXHOST] = {}, sbuf[NI_MAXSERV] = {};

                    in_len = sizeof(in_addr);
                    infd = accept(sfd, &in_addr, &in_len);
                    if (infd == -1)
                    {
                        if (errno == EAGAIN || errno == EWOULDBLOCK)
                        {
                            //we have processed all incoming connections 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ perror_exit函数代码示例发布时间:2022-05-30
下一篇:
C++ perr函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap