本文整理汇总了C++中sleep函数的典型用法代码示例。如果您正苦于以下问题:C++ sleep函数的具体用法?C++ sleep怎么用?C++ sleep使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sleep函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: test_read_and_write_complex_types
static void
test_read_and_write_complex_types (void)
{
int status;
pid_t pid;
ThriftSocket *tsocket = NULL;
ThriftTransport *transport = NULL;
ThriftCompactProtocol *tc = NULL;
ThriftProtocol *protocol = NULL;
int port = TEST_PORT;
/* fork a server from the client */
pid = fork ();
assert (pid >= 0);
if (pid == 0)
{
/* child listens */
thrift_server_complex_types (port);
exit (0);
} else {
/* parent. wait a bit for the socket to be created. */
sleep (1);
/* create a ThriftSocket */
tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost",
"port", port, NULL);
transport = THRIFT_TRANSPORT (tsocket);
thrift_transport_open (transport, NULL);
assert (thrift_transport_is_open (transport));
/* create a ThriftCompactTransport */
tc = g_object_new (THRIFT_TYPE_COMPACT_PROTOCOL, "transport",
tsocket, NULL);
protocol = THRIFT_PROTOCOL (tc);
assert (protocol != NULL);
/* test structures */
assert (thrift_compact_protocol_write_struct_begin (protocol,
NULL, NULL) == 0);
assert (thrift_compact_protocol_write_struct_end (protocol, NULL) == 0);
/* test field state w.r.t. deltas */
assert (thrift_compact_protocol_write_field_begin (protocol, "test",
T_DOUBLE, 1, NULL) == 1);
assert (thrift_compact_protocol_write_field_begin (protocol, "test",
T_DOUBLE,
16, NULL) == 1);
assert (thrift_compact_protocol_write_field_begin (protocol, "test",
T_DOUBLE,
17, NULL) == 1);
assert (thrift_compact_protocol_write_field_begin (protocol, "test",
T_DOUBLE,
15, NULL) > 1);
assert (thrift_compact_protocol_write_field_begin (protocol, "test",
T_DOUBLE,
30, NULL) == 1);
assert (thrift_compact_protocol_write_field_begin (protocol, "test",
T_DOUBLE,
46, NULL) > 1);
assert (thrift_compact_protocol_write_field_begin (protocol, "test",
T_DOUBLE,
47, NULL) == 1);
/* test fields */
assert (thrift_compact_protocol_write_field_begin (protocol, "test",
T_DOUBLE,
1, NULL) > 1);
assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
/* test field state w.r.t. structs */
assert (thrift_compact_protocol_write_field_begin (protocol, "test",
T_DOUBLE,
1, NULL) > 1);
assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
assert (thrift_compact_protocol_write_field_begin (protocol, "test",
T_DOUBLE,
16, NULL) == 1);
assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
assert (thrift_compact_protocol_write_struct_begin (protocol,
NULL, NULL) == 0);
assert (thrift_compact_protocol_write_field_begin (protocol, "test",
T_DOUBLE,
17, NULL) > 1);
assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
assert (thrift_compact_protocol_write_struct_begin (protocol,
NULL, NULL) == 0);
assert (thrift_compact_protocol_write_field_begin (protocol, "test",
T_DOUBLE,
18, NULL) > 1);
assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
assert (thrift_compact_protocol_write_field_begin (protocol, "test",
T_DOUBLE,
19, NULL) == 1);
assert (thrift_compact_protocol_write_field_end (protocol, NULL) == 0);
assert (thrift_compact_protocol_write_struct_end (protocol, NULL) == 0);
//.........这里部分代码省略.........
示例2: main
int main(int argc, char *argv[]) {
int server_coid, self_coid, chid, rcvid;
struct reg_msg msg;
setvbuf (stdout, NULL, _IOLBF, 0);
/* look for server */
server_coid = name_open( RECV_NAME, 0 );
while( server_coid == -1 )
{
sleep(1);
server_coid = name_open( RECV_NAME, 0 );
}
chid = ChannelCreate(0);
if( -1 == chid)
{
perror( PROGNAME "ChannelCreate");
exit( EXIT_FAILURE );
}
self_coid = ConnectAttach( 0, 0, chid, _NTO_SIDE_CHANNEL, 0 );
if( -1 == self_coid )
{
perror( PROGNAME "ConnectAttach");
exit( EXIT_FAILURE );
}
msg.type = REG_MSG;
/* class: Initialize the sigevent structure (msg.ev) in the message
* to be sent to the server.
*/
if (MsgSend( server_coid, &msg, sizeof( msg ), NULL, 0 ) == -1)
{
perror(PROGNAME "MsgSend");
exit( EXIT_FAILURE );
}
while( 1 )
{
rcvid = MsgReceive( chid, &recv_buf, sizeof(recv_buf), NULL );
if( -1 == rcvid )
{
perror(PROGNAME "MsgReceive");
continue;
}
if ( 0 == rcvid )
{
if (MY_PULSE_CODE == recv_buf.pulse.code )
{
printf(PROGNAME "got my pulse\n");
} else
{
printf(PROGNAME "got unexpected pulse with code %d\n",
recv_buf.pulse.code );
}
continue;
}
printf(PROGNAME "got unexpected message, type: %d\n", recv_buf.type );
MsgError( rcvid, ENOSYS );
}
}
示例3: main
int main (int argc, char *argv[]){
///altre variabili
int cont = 0; ///contatore che tiene conto delle cpu, serve per fare cont di fork di processori
///variabili pthread_create
int statusThread;
int statusRam;
/// converto i dati in ingresso forniti dall'utente
numCpu = atoi(argv[1]);
ramDim = atoi(argv[2]);
///una stampa a video per avvertire che i dati immessi dall'utente sono stati acquisiti
if(write(1,"Ho acquisito il numero di processori e la memoria della ram\n",61) == -1) {
write(2,"Write fallita\n",15);
exit(1);
}
///variabili thread
pthread_t threads[numCpu + 1]; /// per tenere traccia degli identificatori delle thread
int *buffers = (int*) malloc((sizeof (int)) * 3);
///inizializzo i semafori
if(pthread_mutex_init(&mutexRam, NULL) != 0){
write(2,"Init fallita\n",14);
exit(1);
}
if(pthread_mutex_init(&mutexProc, NULL) != 0){
write(2,"Init fallita\n",14);
exit(1);
}
if(pthread_mutex_init(&mutexAllProc, NULL) != 0){
write(2,"Init fallita\n",14);
exit(1);
}
if(pthread_mutex_lock(&mutexRam) != 0){
write(2,"Lock fallita\n",14);
exit(1);
}
///valore per far terminare la ram, se 0 non eseguirà mai l'if, se 1 lo esegue ed esce
killRam = 0;
///alloco mememoria e inizializzo le variabili della struct che passarò come argomento quando farò la pthread_create
struttura *parametri = (struttura *)malloc(sizeof(struttura));
parametri->ramDim = ramDim;
parametri->buffer = buffers;
///Creo la thread della ram
if((statusRam = pthread_create(&threads[0], NULL, ram, parametri)) != 0){
write(2,"Non sono riuscito a creare la thread della Ram\n",48);
exit(1);
}
sleep(1); ///aspetto un secondo affinchè la ram posso inizializzare tutti i dati e fermarsi al semaforo in attesa di essere sbloccata
///Creo i numCpu thread
while(cont < numCpu) {
struttura *p = (struttura *)malloc(sizeof(struttura));
p->nProc = cont;
p->buffer = buffers;
if((statusThread = pthread_create(&threads[cont + 1], NULL, processore2, p)) != 0) {
write(2,"Non sono riuscito a creare la thread\n",38);
exit(1);
}
cont++;
}
///il processo padre aspetta che tutti le thread figlie terminino per poter terminare pure lui
for(cont = 0; cont < numCpu; cont++)
if(pthread_join(threads[cont + 1], NULL) != 0){
write(2,"Join fallita\n",14);
exit(1);
}
killRam = 1;
if(pthread_mutex_unlock(&mutexRam) != 0){
write(2,"Unlock fallita\n",16);
exit(1);
}
if(pthread_join(threads[0], NULL) != 0){
write(2,"Join fallita\n",14);
exit(1);
}
int i;
///distruggo i semafori
if((i = pthread_mutex_destroy(&mutexRam)) != 0){
//write(2,"Destroy fallita\n",17);
exit(1);
}
if((i = pthread_mutex_destroy(&mutexProc)) != 0){
write(2,"Destroy fallita\n",17);
exit(1);
}
//.........这里部分代码省略.........
示例4: while
void Socket::socketThread() {
Json::Reader reader;
bool running = true;
int addrinfo_status, connect_status, socket_status = 0;
while ( running ) {
if ( !socketfd || socket_status ) {
struct addrinfo host_info;
struct addrinfo *host_info_list;
// Close the existing socket, if it has been left open.
if ( socketfd ) {
close( socketfd );
socketfd = NULL;
}
// Establish connection
memset( &host_info, 0, sizeof host_info );
host_info.ai_family = AF_UNSPEC;
host_info.ai_socktype = SOCK_STREAM;
addrinfo_status = getaddrinfo( hostname, port, &host_info, &host_info_list );
if ( addrinfo_status ) {
std::cout << "couldn't get address" << std::endl ;
sleep(1);
continue;
}
socketfd = socket( host_info_list->ai_family, host_info_list->ai_socktype, host_info_list->ai_protocol );
if ( socketfd == -1 ) {
socket_status = -1;
std::cout << "socket error" << std::endl ;
sleep(1);
continue;
}
connect_status = connect( socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen );
if ( connect_status ) {
socket_status = -1;
std::cout << "connect error" << std::endl ;
sleep(1);
continue;
}
socket_status = 0;
}
int max_message_size = 1000000;
ssize_t bytes_recieved;
struct hss_header header;
string buffer;
bytes_recieved = recv( socketfd, &header, sizeof header, 0 );
//std::cout << "received " << bytes_recieved << std::endl;
if ( bytes_recieved == sizeof header ) {
// Parse the header ( what there is of it )
header.string_bytes = ntohl( header.string_bytes );
if ( header.string_bytes > max_message_size ) {
// Bad header, fuck it.
socket_status = -3;
std::cout << "bad header, disconnecting";
continue;
}
buffer.resize( header.string_bytes );
size_t b = recv( socketfd, (void * ) buffer.c_str(), header.string_bytes, MSG_WAITALL );
if ( b != header.string_bytes ) {
}
Json::Value msg;
//std::cout << buffer << std::endl;
reader.parse( buffer, msg );
Json::Value set = msg["set"];
if ( set.isObject() ) {
Json::Value set = msg["set"];
for ( Json::ValueIterator i = set.begin(); i != set.end(); i ++ ) {
string k = (string) i.memberName();
horten->set( set[k], k, flags );
}
}
//.........这里部分代码省略.........
示例5: xsh_suspend
shellcmd xsh_suspend( int nargs, char *args[] )
{
tid_typ tid; /* tid for thread to suspend */
/* Output help, if '--help' argument was supplied */
if( nargs == 2 && strncmp( args[1], "--help", 7 ) == 0)
{
printf("Usage: %s <TID>\n\n", args[0]);
printf("Description:\n");
printf("\tSuspends thread with the identifier TID.\n");
printf("Options:\n");
printf("\t<TID>\tID of thread to suspend.\n");
printf("\t--help\tdisplay this help and exit\n");
return 0;
}
/* Check for correct number of arguments */
if( nargs < 2 )
{
fprintf(stderr, "%s: missing operand\n", args[0]);
fprintf(stderr, "Try '%s --help' for more information.\n", args[0]);
return 1;
}
if( nargs > 2 )
{
fprintf(stderr, "%s: too many arguments.\n", args[0]);
fprintf(stderr, "Try '%s --help' for more information.\n", args[0]);
return 1;
}
tid = atoi( args[1] );
/* Don't try to suspend a null thread */
if( tid == NULLTHREAD )
{
fprintf( stderr, "%s: (%d) Operation not permitted.\n", args[0], tid);
return 1;
}
//If shell is being suspended, print notice to shell.
if( tid == gettid() )
{
fprintf( stderr, "%s: Shell suspended.\n", args[0] );
sleep(2000);
}
//Suspend thread, nothing is suspend failed.
if( suspend( tid ) == SYSERR )
{
fprintf( stderr, "%s : (%d) No such thread.\n", args[0], tid);
return -1;
}
return 0;
}
示例6: configpalen_ipdetaup
//---------------------------------------------------
// 自动返回控制器器IP主函数
//---------------------------------------------------
//int main(int argc, char *argv[])
int configpalen_ipdetaup(void)
{
int s_fd=0;
int ret = 0;
int i = 0;
unsigned char sys_id[6];
unsigned char buf[64];
unsigned char request_buf[13];
unsigned char h_ip[4];
unsigned char s_ip[16];
unsigned char s_gw[16];
//unsigned char *ip="192.172.1.125";
unsigned char setip[32] = "ifconfig eth0 ";
int s_len = strlen(setip);
unsigned char setgw[64] = "route add default gw ";
int g_len = strlen(setgw);
unsigned char k_ip[4];
unsigned char smk[6];
int sys_id_flag = 0;
read_identifier(sys_id);//读取identifier.ini中保存的信息
request_buf[0] = CAM_TYPE_TOP1;
request_buf[1] = CAM_TYPE_TOP2;
request_buf[2] = CAM_TYPE_REPLY;
memcpy(request_buf+3, sys_id, 6);
unsigned char versionbuf[2];
//获取系统本身IP
//ret = save_system_ip(ip, strlen(ip));
ret = read_txt_ip(s_ip, h_ip);//读取systemip.ini中的信息
if(ret < 0)
{
//获取文本的IP错误
printf("read system ip file error!!!\n");
GetIP_v4_and_v6_linux(AF_INET,s_ip,16); //获取系统的IP
ret = save_system_ip(s_ip, strlen(s_ip));
}
/*//printf("s_ip=%s\n",s_ip);
memcpy(setip+s_len, s_ip, strlen(s_ip)+1);
printf("set ip:%s\n",setip);
system(setip);//还进行了设置。
myread_txt_ip(s_gw, h_ip);
memcpy(setgw+g_len, s_gw, strlen(s_gw)+1);
printf("set gateway:%s\n",setgw);
system(setgw);*/
s_fd = make_send_multicast_init(s_ip); //创建主播发送字符,只使用一个套接字也完全可以的。ghf
socklen_t len=sizeof(addr);
extern int errno;
static int val=0;
cpufd = open("/dev/cpu_led",O_RDONLY);
if (cpufd < 0)
{
system("insmod cpu_led.ko");
sleep(2);
cpufd = open("/dev/cpu_led",O_RDONLY);
if (cpufd < 0){
printf("error,open device cpu_led!!!\n");
}
}
else{
printf("open device cpu_led!!!\n");
}
//此接口走路由不行,但直连不同字段都可以
struct sockaddr_in peeraddr;
bzero(&peeraddr, sizeof(peeraddr));
peeraddr.sin_family = AF_INET;
peeraddr.sin_port = htons(MUTIL_PORT);
peeraddr.sin_addr.s_addr = inet_addr(MUTIL_ADDR);
while(1)
{
//防止arm端ip被改
GetIP_v4_and_v6_linux(AF_INET,s_ip,16);
save_system_ip(s_ip, strlen(s_ip));
val++;
ret = recvfrom(s_fd, buf, 64, 0, (struct sockaddr*)&addr, &len);//最后一个参数的定义跟sendto不一样,注意!
//.........这里部分代码省略.........
示例7: utmpx_mark_init
int
utmpx_mark_init(pid_t pid, char *prefix)
{
struct utmpx ut, *oldu;
int tmplen;
int ret;
while (st->st_initial && !utmpx_truncated)
(void) usleep(200 * USEC_PER_MSEC);
/*
* Clean out any preexisting records for this PID, as they must be
* inaccurate.
*/
utmpx_mark_dead(pid, 0, B_TRUE);
/*
* Construct a new record with the appropriate prefix.
*/
(void) memset(&ut, 0, sizeof (ut));
(void) strncpy(ut.ut_user, ".startd", sizeof (ut.ut_user));
ut.ut_pid = pid;
ut.ut_id[0] = ut.ut_id[1] = ut.ut_id[2] = ut.ut_id[3] = (char)SC_WILDC;
for (ret = 0; ret < strlen(prefix); ret++)
ut.ut_id[ret] = prefix[ret];
ut.ut_type = INIT_PROCESS;
(void) time(&ut.ut_tv.tv_sec);
for (;;) {
MUTEX_LOCK(&utmpx_lock);
setutxent();
if ((oldu = getutxid(&ut)) != NULL) {
/*
* Copy in the old "line" and "host" fields.
*/
bcopy(oldu->ut_line, ut.ut_line, sizeof (ut.ut_line));
bcopy(oldu->ut_host, ut.ut_host, sizeof (ut.ut_host));
ut.ut_syslen = (tmplen = strlen(ut.ut_host)) ?
min(tmplen + 1, sizeof (ut.ut_host)) : 0;
}
if (makeutx(&ut) != NULL)
break;
if (errno != EROFS)
log_framework(LOG_WARNING,
"makeutx failed, retrying: %s\n", strerror(errno));
MUTEX_UNLOCK(&utmpx_lock);
(void) sleep(1);
}
updwtmpx(WTMPX_FILE, &ut);
endutxent();
MUTEX_UNLOCK(&utmpx_lock);
return (ret);
}
示例8: main
//.........这里部分代码省略.........
atpb.atp_rresiovcnt = 1;
if ( atp_rresp( satp, &atpb ) < 0 ) {
perror( "atp_rresp" );
continue;
}
#ifndef NONZEROSTATUS
/*
* The stinking LaserWriter IINTX puts crap in this
* field.
*/
if ( ((char *)rniov[ 0 ].iov_base)[ 0 ] != 0 ) {
fprintf( stderr, "Bad status response!\n" );
exit( 1 );
}
#endif /* NONZEROSTATUS */
if ( ((char *)rniov[ 0 ].iov_base)[ 1 ] != PAP_STATUS ||
atpb.atp_rresiovcnt != 1 ) {
fprintf( stderr, "Bad status response!\n" );
exit( 1 );
}
if(debug){ printf( "< STATUS\n" ), fflush( stdout );}
memcpy( st_buf, (char *) rniov[ 0 ].iov_base + 9,
((char *)rniov[ 0 ].iov_base)[ 8 ] );
st_buf[ (int) ((char *)rniov[ 0 ].iov_base)[ 8 ]] = '\0';
if ( strstr( st_buf, "idle" ) != NULL ) {
waitforidle = 0;
} else {
updatestatus( (char *) rniov[ 0 ].iov_base + 9,
((char *)rniov[ 0 ].iov_base)[ 8 ] );
sleep( 5 );
}
}
cbuf[ 0 ] = connid = getpid() & 0xff;
cbuf[ 1 ] = PAP_OPEN;
cbuf[ 2 ] = cbuf[ 3 ] = 0;
cbuf[ 4 ] = atp_sockaddr( atp )->sat_port;
cbuf[ 5 ] = oquantum; /* flow quantum */
if ( gettimeofday( &stv, NULL ) < 0 ) {
perror( "gettimeofday" );
exit( 2 );
}
for (;;) {
if ( cuts ) {
waiting = 0xffff;
} else {
if ( gettimeofday( &tv, NULL ) < 0 ) {
perror( "gettimeofday" );
exit( 2 );
}
waiting = htons( tv.tv_sec - stv.tv_sec );
}
memcpy(cbuf + 6, &waiting, sizeof( waiting ));
atpb.atp_saddr = &nn.nn_sat;
atpb.atp_sreqdata = cbuf;
atpb.atp_sreqdlen = 8; /* bytes in OpenConn request */
atpb.atp_sreqto = 2; /* retry timer */
atpb.atp_sreqtries = 5; /* retry count */
if ( atp_sreq( atp, &atpb, 1, ATP_XO ) < 0 ) {
perror( "atp_sreq" );
exit( 1 );
示例9: main
main(int argc, char *argv[])
{
int i, j, l;
int ch;
extern char *optarg;
int edge;
int size;
int lu_arg[MAX_THREADS][3];
/* ARMCI */
void **ptr;
double **ptr_loc;
THREAD_LOCK_INIT(mutex);
armci_msg_init(&argc,&argv);
nproc = armci_msg_nproc();
me = armci_msg_me();
while ((ch = getopt(argc, argv, "n:b:p:t:d:h")) != -1) {
switch(ch) {
case 'n': n = atoi(optarg); break;
case 'b': block_size = atoi(optarg); break;
case 'p': nproc = atoi(optarg); break;
case 't': th_per_p = atoi(optarg); break;
case 'd': d = atoi(optarg); break;
case 'h': {
printf("Usage: LU, or \n");
printf(" LU -nMATRIXSIZE -bBLOCKSIZE -pNPROC -tTH_PER_P\n");
armci_msg_barrier();
armci_msg_finalize();
exit(0);
}
}
}
if(th_per_p>MAX_THREADS) {
th_per_p=MAX_THREADS;
if(me==0)printf("Warning: cannot run more than %d threads, adjust MAX_THREADS",MAX_THREADS);
}
if (d) {
fprintf(stderr, "%d: %d\n", me, getpid());
sleep(d);
}
nthreads = th_per_p * nproc;
if(me == 0) {
printf("\n Blocked Dense LU Factorization\n");
printf(" %d by %d Matrix\n", n, n);
printf(" %d Processors\n", nproc);
printf(" %d thread(s) per processor, %d threads total\n", th_per_p, nthreads);
printf(" %d by %d Element Blocks\n", block_size, block_size);
printf("\n");
}
num_rows = (int) sqrt((double) nthreads);
for (;;) {
num_cols = nthreads/num_rows;
if (num_rows*num_cols == nthreads)
break;
num_rows--;
}
nblocks = n/block_size;
if (block_size * nblocks != n) {
nblocks++;
}
num = (nblocks * nblocks)/nthreads;
if((num * nthreads) != (nblocks * nblocks))
num++;
edge = n%block_size;
if (edge == 0) {
edge = block_size;
}
#ifdef DEBUG
if(me == 0)
for (i=0;i<nblocks;i++) {
for (j=0;j<nblocks;j++)
printf("%d ", block_owner(i, j));
printf("\n");
}
armci_msg_barrier();
/* armci_msg_finalize(); */
/* exit(0); */
#endif
for (l = 0; l < th_per_p; l++) {
me_th[l] = me * th_per_p + l;
for (i=0;i<nblocks;i++) {
for (j=0;j<nblocks;j++) {
if(block_owner(i,j) == me_th[l]) {
if ((i == nblocks-1) && (j == nblocks-1)) {
size = edge*edge;
}
else if ((i == nblocks-1) || (j == nblocks-1)) {
size = edge*block_size;
}
//.........这里部分代码省略.........
示例10: main
int main (int argc, char *argv[])
{
unsigned int outfile_p, outfile, device, i, seek, last_blk, sprint_size, flag = 0;
char *buf, *buf_test, c, *buf_prev, buf2[1000];
struct timespec start, end;
unsigned long long local_nsec;
if (argc < 4) {
printf("Usage <a.out> \"device/file path\" <blocks to test> <character>\n");
exit (1);
}
system("/ssdoptfs/drcontrol.py -d DAE0010T -r all -c on");
sleep(10);
for(i = 0; i < 1000; i++) {
buf2[i] = '\0';
}
if ((device = open(argv[1], O_RDWR, O_SYNC)) == -1) {
printf("Could not open device, exiting\n");
exit(1);
}
unlink(OUT_FILE);
unlink(OUT_FILE_P);
if ((outfile = open(OUT_FILE, O_RDWR | O_CREAT, O_SYNC)) == -1) {
printf("Could not open output file, exiting\n");
exit(1);
}
if ((outfile_p = open(OUT_FILE_P, O_RDWR | O_CREAT, O_SYNC)) == -1) {
printf("Could not open output file, exiting\n");
exit(1);
}
// Allocate buffer
if ((buf = (char *)malloc(BLOCK_SIZE)) == NULL) {
printf("Could not allocate buffer, exiting\n");
exit(1);
}
if ((buf_test = (char *)malloc(BLOCK_SIZE)) == NULL) {
printf("Could not allocate buffer, exiting\n");
exit(1);
}
/*if ((buf_prev = (char *)malloc(BLOCK_SIZE)) == NULL) {
printf("Could not allocate buffer, exiting\n");
exit(1);
}*/
c = *argv[3];
printf("\n");
last_blk = atoi(argv[2]);
// Fill buffer
for (i = 0; i < BLOCK_SIZE; i++) {
*(buf + i) = c;
}
for(seek = 0; seek <= last_blk; seek++) {
if (lseek(device, seek * BLOCK_SIZE, SEEK_SET) == -1) {
printf("Seek failed, blknbr %d\n", seek);
}
if ((read(device, buf_test, BLOCK_SIZE) == -1)) {
printf("A read failed, blknbr %d\n", seek);
break;
}
// memcpy(buf_prev, buf, BLOCK_SIZE);
if (memcmp(buf, buf_test, BLOCK_SIZE)) {
flag = 1;
sprint_size = sprintf(buf2, "Inconsistent write detected at blknbr %d, sector %d\n", seek, seek * 8);
write (outfile, buf2, sprint_size);
for(i = 0; i < BLOCK_SIZE; i++) {
if (*(buf_test + i) == c) {
printf("partial write detected\n");
sprint_size = sprintf(buf2, "Partial Inconsistent Write detected blknbr %d, sector %d\n", seek, seek * 8);
write (outfile_p, buf2, sprint_size);
write (outfile_p, buf_test, BLOCK_SIZE);
write (outfile_p, "\n", 1);
}
}
} else if (flag) {
printf("out of order write!!\n");
}
}
// printf("Differing block : %s \n",buf_test);
// printf("Previous block : %s \n",buf_prev);
printf("normal exit\n");
close(device);
close(outfile);
close(outfile_p);
return;
//.........这里部分代码省略.........
示例11: internal__hydra_connect
int
internal__hydra_connect(unsigned long int host, int port, int protocol, int type)
{
int s, ret = -1;
struct sockaddr_in target;
char *buf, *tmpptr = NULL;
struct sockaddr_in sin;
#ifndef CYGWIN
char out[16];
#endif
if ((s = socket(PF_INET, protocol, type)) >= 0) {
if (src_port != 0)
{
int bind_ok=0;
sin.sin_family = PF_INET;
sin.sin_port = htons(src_port);
sin.sin_addr.s_addr = INADDR_ANY;
//we will try to find a free port down to 512
while (!bind_ok && src_port >= 512)
{
if (bind(s, (struct sockaddr *)&sin, sizeof(sin))==-1)
{
if (verbose)
perror("error:");
if (errno == EADDRINUSE)
{
src_port--;
sin.sin_port = htons(src_port);
}
else
{
if (errno == EACCES && (getuid() > 0))
{
printf("You need to be root to test this service\n");
return -1;
}
}
}
else
bind_ok=1;
}
}
if (use_proxy > 0) {
target.sin_port = htons(proxy_string_port);
memcpy(&target.sin_addr.s_addr, &proxy_string_ip, 4);
} else {
target.sin_port = htons(port);
memcpy(&target.sin_addr.s_addr, &host, 4);
}
target.sin_family = AF_INET;
signal(SIGALRM, alarming);
do {
if (fail > 0)
sleep(WAIT_BETWEEN_CONNECT_RETRY);
alarm_went_off = 0;
alarm(waittime);
ret = connect(s, (struct sockaddr *) &target, sizeof(target));
alarm(0);
if (ret < 0 && alarm_went_off == 0) {
fail++;
if (verbose && fail <= MAX_CONNECT_RETRY)
fprintf(stderr, "Process %d: Can not connect [unreachable], retrying (%d of %d retries)\n", (int) getpid(), fail, MAX_CONNECT_RETRY);
}
} while (ret < 0 && fail <= MAX_CONNECT_RETRY);
if (ret < 0 && fail > MAX_CONNECT_RETRY) {
if (debug)
printf("DEBUG_CONNECT_UNREACHABLE\n");
/* we wont quit here, thats up to the module to decide what to do
* fprintf(stderr, "Process %d: Can not connect [unreachable], process exiting\n", (int)getpid());
* hydra_child_exit(1);
*/
extern_socket = -1;
ret = -1;
return ret;
}
ret = s;
extern_socket = s;
if (debug)
printf("DEBUG_CONNECT_OK\n");
if (use_proxy == 2) {
buf = malloc(4096);
memset(&target, 0, sizeof(target));
memcpy(&target.sin_addr.s_addr, &host, 4);
target.sin_family = AF_INET;
#ifdef CYGWIN
if (proxy_authentication == NULL)
snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\n\r\n", inet_ntoa((struct in_addr) target.sin_addr), port);
else
snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\nProxy-Authorization: Basic %s\r\n\r\n", inet_ntoa((struct in_addr) target.sin_addr), port, proxy_authentication);
#else
if (proxy_authentication == NULL)
snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\n\r\n", inet_ntop(AF_INET, &target.sin_addr, out, sizeof(out)), port);
else
snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\nProxy-Authorization: Basic %s\r\n\r\n", inet_ntop(AF_INET, &target.sin_addr, out, sizeof(out)), port,
proxy_authentication);
//.........这里部分代码省略.........
示例12: main
int main()
{
char mqname[NAMESIZE], msgrv[BUFFER];
mqd_t mqdes;
struct timespec ts;
time_t oldtime, newtime;
struct mq_attr attr;
pid_t pid;
int unresolved = 0, failure = 0;
sprintf(mqname, "/" FUNCTION "_" TEST "_%d", getpid());
attr.mq_msgsize = BUFFER;
attr.mq_maxmsg = BUFFER;
mqdes = mq_open(mqname, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, &attr);
if (mqdes == (mqd_t)-1) {
perror(ERROR_PREFIX "mq_open");
unresolved = 1;
}
pid = fork();
if (pid != 0) {
/* Parent process */
struct sigaction act;
act.sa_handler = exit_handler;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGABRT, &act, 0);
#ifdef _POSIX_TIMERS
printf("Using CLOCK_REALTIME\n");
clock_gettime(CLOCK_REALTIME, &ts);
oldtime = ts.tv_sec;
ts.tv_sec = ts.tv_sec + TIMEOUT;
#else
ts.tv_sec = time(NULL) + TIMEOUT;
oldtime = time(NULL);
#endif
ts.tv_nsec = 0;
mq_timedreceive(mqdes, msgrv, BUFFER, NULL, &ts);
#ifdef _POSIX_TIMERS
clock_gettime(CLOCK_REALTIME, &ts);
newtime = ts.tv_sec;
#else
newtime = time(NULL);
#endif
if ((newtime - oldtime) < TIMEOUT) {
printf("FAIL: mq_timedreceive didn't block until "
"timout expires\n");
failure = 1;
}
/* Parent is not blocking, let child abort */
kill(pid, SIGABRT);
wait(NULL);
if (mq_close(mqdes) != 0) {
perror(ERROR_PREFIX "mq_close");
unresolved = 1;
}
if (mq_unlink(mqname) != 0) {
perror(ERROR_PREFIX "mq_unlink");
unresolved = 1;
}
if (failure == 1 || blocking == 1) {
printf("Test FAILED\n");
return PTS_FAIL;
}
if (unresolved == 1) {
printf("Test UNRESOLVED\n");
return PTS_UNRESOLVED;
}
printf("Test PASSED\n");
return PTS_PASS;
} else {
sleep(TIMEOUT + 3); /* Parent is probably blocking
send a signal to let it abort */
kill(getppid(), SIGABRT);
return 0;
}
}
示例13: videoset
////////////////////////////////////////////////////////////////////////////
// Function: netset
////////////////////////////////////////////////////////////////////////////
int videoset(char **postvars, int form_method)
{
FILE *fffd,*fp, *vsfd;
unsigned long ulTemp;
unsigned char ucbuf[sizeof(video_conf)];
int iTemp, i, size;
char pctmp[40];
char iptmp[20];
// HTML header, print it here
printf("Content-type: text/html\r\n\r\n");
printf("\r\n\r\n");
printf("<html><head></head>");
fflush(stdout);
usleep(1000);
// If we got post, write it into flash
if(form_method == POST)
{
printf("<body><center><BR><font style=\"font-size:12pt\" face=\"Arial\">");
// Read and preserve content from flash to buffer
GetConfValues();
for (i=0; postvars[i]; i+= 2)
{
#if DEBUG
printf("DEBUG: [%s] = [%s]<br>", postvars[i], postvars[i+1]);
#endif
// Parse for video port
if(!strcmp(postvars[i], "VIDEOPORT"))
{
CONF_VIDEO->ServerPort = (unsigned short)atoi(postvars[i+1]);
}
// parse for quality method
if(!strcmp(postvars[i], "QUALITYMETHOD"))
{
if(!strcmp(postvars[i+1], "1"))
CONF_VIDEO->QualityMethod = 1;
else if(!strcmp(postvars[i+1], "2"))
CONF_VIDEO->QualityMethod = 2;
}
// parse for bitrate
if(!strcmp(postvars[i], "BITRATE"))
{
if(!strcmp(postvars[i+1], "1"))
CONF_VIDEO->BitRate = 1;
else if(!strcmp(postvars[i+1], "2"))
CONF_VIDEO->BitRate = 2;
else if(!strcmp(postvars[i+1], "3"))
CONF_VIDEO->BitRate = 3;
else if(!strcmp(postvars[i+1], "4"))
CONF_VIDEO->BitRate = 4;
else if(!strcmp(postvars[i+1], "5"))
CONF_VIDEO->BitRate = 5;
else if(!strcmp(postvars[i+1], "6"))
CONF_VIDEO->BitRate = 6;
else if(!strcmp(postvars[i+1], "7"))
CONF_VIDEO->BitRate = 7;
else if(!strcmp(postvars[i+1], "8"))
CONF_VIDEO->BitRate = 8;
else if(!strcmp(postvars[i+1], "9"))
CONF_VIDEO->BitRate = 9;
else if(!strcmp(postvars[i+1], "10"))
CONF_VIDEO->BitRate = 10;
else if(!strcmp(postvars[i+1], "11"))
CONF_VIDEO->BitRate = 11;
}
// parse for quality
if(!strcmp(postvars[i], "QUALITY"))
{
if(!strcmp(postvars[i+1], "1"))
CONF_VIDEO->Quality = 1;
else if(!strcmp(postvars[i+1], "2"))
CONF_VIDEO->Quality = 2;
else if(!strcmp(postvars[i+1], "3"))
CONF_VIDEO->Quality = 3;
else if(!strcmp(postvars[i+1], "4"))
CONF_VIDEO->Quality = 4;
else if(!strcmp(postvars[i+1], "5"))
CONF_VIDEO->Quality = 5;
}
// parse for resolution
if(!strcmp(postvars[i], "RESOLUTION"))
{
if(!strcmp(postvars[i+1], "1"))
CONF_VIDEO->Resolution = 1;
else if(!strcmp(postvars[i+1], "2"))
CONF_VIDEO->Resolution = 2;
else if(!strcmp(postvars[i+1], "3"))
CONF_VIDEO->Resolution = 3;
else if(!strcmp(postvars[i+1], "4"))
//.........这里部分代码省略.........
示例14: main
int main(int argc, char **argv)
{
char dir[BUFSIZ];
struct sock_cl s;
pid_t child_id;
int addrlen;
int status;
struct question *q; /* are we going to recycle the same data structure over and over again */
if(argc != 3) {
fprintf(stderr, "USAGE: ./udp_client ip_address port_number\n");
return -1;
}
if(argv[1])
strcpy(hostname, argv[1]);
else
strcpy(hostname, HOST);
if(argv[2])
s.port = atoi(argv[2]);
else
s.port = port;
while(obtain_req_type(dir) != 0){
fprintf(stderr, "Still no request for client\n");
sleep(2);
}
populate_sock(&s);
addrlen = s.addrlen;
ap_debug("====>Client side port = %d", port);
/* All transaction are started by client, so it is client which will either ask
* 1. server to send the question or
* 2. process the question send by the user.
* in case 1. the user has already asked the question and waiting for response
* in case 2. user pushes a question. server sends it to another client, who wants to answer the question
* server waits for the response from the user, as soon as response is available,
* the server pushes the question back to first client
*/
ap_debug("%p\n",&s.sin);
while(1) {
switch(query_type(dir))
{
/* Begin set 1 reqQ-saveA */
case REQ_QUESTION:
strcpy(s.buffer, dir);
client_req_ques(&s);
q = (struct question *)malloc(sizeof(struct question));
populate_ques_ds(question_file, q);
strcpy(dir, s.buffer);
break;
/* set 2 reqA-saveQ End */
case REQ_ANSWER:
strcpy(s.buffer, dir);
client_req_ans(&s);
strcpy(dir, req_type[REQ_STOP]);
break;
/* Begin set 2 saveQ-reqA */
case SAVE_QUESTION:
/* CAUTION dir and s.buffer contain different values */
memset(s.buffer, 0, sizeof(s.buffer));
/* open the question file and populate question data structure */
q = (struct question *)malloc(sizeof(struct question));
populate_ques_ds(question_file, q);
create_qbuf(q,s.buffer);
client_save_ques(&s, dir); /* dir is populated inside here */
free_question(q);
break;
/* set 1 saveA-reqQ End */
case SAVE_ANSWER:
if( access( answer_file, F_OK ) == -1 )
continue;
/* obtain answer in the buffer */
/* open the answer file and fill the buffer */
memset(s.buffer, 0, sizeof(s.buffer));
populate_if_match(q, answer_file); /* obtain data structure for question */
create_abuf(q, s.buffer);
client_save_ans(&s, dir);
strcpy(dir, req_type[REQ_STOP]);
free_question(q);
break;
case REQ_STOP:
/* do any cleanup here? */
return 0;
case REQ_LOOP:
/* do any cleanup here? */
break;
default:
case -1:
fprintf(stderr, "What the fuck bro?\n");
exit(EXIT_FAILURE);
}
sleep(1);
}
return 0;
}
示例15: tty_serial_read
//read one total frame and load the data section(except for the start three bytes) into buf
//and return the length of it(including the checksum bit)
int tty_serial_read(int fds, String tbuf) {
if(fds<0 || !tbuf) PARAMETER_ERROR("tty_serial_read");
if(tbuf[0]) memset(tbuf,0,MAX_FRAME_SIZE);
while(tbuf[0]!='~') {
if(read(fds,tbuf,1)<0) {
perror("reading ttyUSB0");
sleep(2);
}
}
tbuf++; //point to the new position
ssize_t ret;
int i,bytes=1,leng = 2; //bytes:bytes already read, length: bytes to read
while (leng!=0 && (ret=read(fds,tbuf,leng))!=0) {
if(ret==-1) {
if(errno==EINTR)
continue;
perror("read the starting 3 bytes"); //no data available in non-blocking mode or other errors
sleep(2);
return -1;
}
leng -= ret;
tbuf += ret;
}
bytes += 2;
leng = inbuf[1]*256 + inbuf[2] +1; //including the checksum bit, be careful to use inbuf cauze tbuf is moving!!
printf("received data section length including the checksum: %d seq: %d\n",leng,inbuf[38]);
//continue reading the followint bytes of length leng and check escape
int nr_escapes = leng;
do {
leng = nr_escapes;
while (leng!=0 && (ret=read(fds,tbuf,leng))!=0) {
if(ret==-1) {
if(errno==EINTR)
continue;
perror("read the data section error");
sleep(1);
return -1;
}
leng -= ret;
tbuf += ret;
}
bytes += nr_escapes;
int i, leng = nr_escapes;
nr_escapes = 0;
for(i=bytes-leng;i<bytes;i++) { //check the newly read bytes
if(inbuf[i]==0x7D) {
printf("the byte after escape: %d %d\n",i, inbuf[i+1]);
//int c = tbuf[1+i];
//if(c==0x7E || c==0x11 || c==0x13 || c==0x7D) {
nr_escapes++;
}
}
} while(nr_escapes);
#ifndef DEBUG
leng = bytes;
String fbuf = inbuf;
int logfds = open("./esclog.txt", O_CREAT | O_RDWR | O_APPEND);
while (leng!=0 && (ret=write(logfds,fbuf,leng))!=0) {
if(ret==-1) {
if(errno==EINTR)
continue;
perror("wrinting to log file");
}
leng -= ret;
fbuf += ret;
}
if(close(logfds)==-1) perror("close esclog file");
#endif
//descape and check checksum
bytes = xbee_frame_descape(inbuf,bytes);
if(xbee_set_checksum(&inbuf[3],bytes-3)!=0) {
printf("%s\n","checksum error...");
//memset(inbuf,0,bytes);
return 0;
} else {
printf("%s total bytes after descape: %d seq: %d\n","checksum perfect!",bytes,);
}
#ifndef DEBUG
leng = bytes;
fbuf = inbuf;
int dlogfds = open("./esclog.txt", O_CREAT | O_RDWR | O_APPEND);
while (leng!=0 && (ret=write(dlogfds,fbuf,leng))!=0) {
if(ret==-1) {
if(errno==EINTR)
continue;
perror("wrinting to dlog file");
}
leng -= ret;
fbuf += ret;
}
//.........这里部分代码省略.........