当前位置: 首页>>代码示例>>C++>>正文


C++ perror函数代码示例

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


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


注:本文中的perror函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。