int main(int argc, char *argv[]) { int opt; Boolean append; if (argc != 2) usage_err("%s [-a] outfile\n", argv[0]); while ((opt = getopt(argc, argv, ":a")) != -1) { switch (opt) { case 'a': append = TRUE; break; case ':': usage_err("missing argument"); case '?': usage_err("unknown option"); default: fatal("Unexpected case in switch()"); } } char *outfile = argv[optind]; int fd; if (append == TRUE) fd = open(outfile, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR); else fd = open(outfile, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); if (fd == -1) err_exit("open"); int bytes_read, bytes_written; char buf[128]; while ((bytes_read = read(STDIN_FILENO, buf, sizeof(buf)))) { bytes_written = write(STDOUT_FILENO, buf, bytes_read); if (bytes_written != bytes_read) err_exit("bytes_written != bytes_read stdout"); bytes_written = write(fd, buf, bytes_read); if (bytes_written != bytes_read) err_exit("bytes_written != bytes_read fd"); } if (close(fd)) err_exit("close"); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { int s, sig; if (argc != 3 || strcmp(argv[1], "--help") == 0) usage_err("%s sig-num pid\n", arg[0]); sig = get_int(argv[2], 0, "sig-num"); if (sig != 0) { if (s == -1) err_exit("kill"); }else { if (s == 0) { printf("Process exists and we can send it a signal\n"); }else { if (errno == EPERM) printf("Process exists, but we don't have permission to send it a signal\n"); else if (errno == ESRCH) printf("Process does not exists\n"); else err_exit("kill"); } } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { if (argc < 2 || strcmp(argv[1], "--help") == 0) usage_err("%s temp-file [num-1kb-blocks]\n", argv[0]); char shell_cmd[CMD_SIZE]; char buf[BUF_SIZE]; int num_blocks = argc > 2 ? get_int(argv[2], GN_GT_0, "num_blocks") : 10000; int fd = open(argv[1], O_WRONLY | O_CREAT | O_EXCL, S_IWUSR); if (fd < 0) err_exit("open"); if (unlink(argv[1]) < 0) err_exit("unlink"); for (int i = 0; i < num_blocks; i++) if(write(fd, buf, BUF_SIZE) != BUF_SIZE) fatal("partial/failed write"); snprintf(shell_cmd, CMD_SIZE, "df -k $(dirname %s)", argv[1]); system(shell_cmd); if (close(fd) < 0) err_exit("close"); printf("******** Closed file descriptor\n"); system(shell_cmd); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { struct stat *sb; boolean stat_link; int fname; stat_link = (argc > 1) && strcmp(argv[1], "-l") == 0; fname = stat_link ? 2 : 1; if (fname >= argc || (argc > 1 && strcmp(argv[1], "--help") == 0)) usage_err("%s [-l] file\n" " -l = use lstat() instead of stat()\n", argv[0]); if (stat_link) { if (lstat(argv[fname], &sb) == -1) err_exit("lstat"); }else { if (stat(argv[fname], &sb) == -1) err_exit("stat"); } display_stat_info(&sb); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int j, sig_cnt; sigset_t block_mask, empty_mask; struct sigaction sa; if (argc < 2 || strcmp(argv[1], "--help") == 0) usage_err("%s child-sleep-time...\n", argv[0]); setbuf(stdout, NULL); sig_cnt = 0; num_live_children = argc - 1; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = sig_child_handler; if (sigaction(SIGCHLD, &sa, NULL) == -1) err_exit("sigaction"); /* * Block SIGCHLD to prevent its delivery if a child terminates * before the parent commences the sigsuspend() loop below */ sigemptyset(&block_mask); sigaddset(&block_mask, SIGCHLD); if (sigprocmask(SIG_SETMASK, &block_mask, NULL) == -1) err_exit("sigprocmask"); for (j = 1; j < argc; j++) { switch(fork()) { case -1: err_exit("fork"); case 0: sleep(get_int(argv[j], GN_NONNEG, "child-sleep-time")); printf("%s Child %d (PID=%ld) exiting\n", curr_time("%T"), j, (long)getpid()); _exit(EXIT_SUCCESS); default: break; } } /* Parent come here: wait for SIGCHLD until all children are dead */ while(num_live_children > 0) { if (sigsuspend(&empty_mask) == -1 && errno != EINTR) err_exit("sigsuspend"); sig_cnt++; } printf("%s All %d children have terminated; SIGCHLD was caught %d times\n", curr_time("%T"), argc - 1, sig_cnt); }
int main(int argc, char* argv[]) { int c; while( (c = getopt(argc, argv, "hs:r:dp:")) != -1 ) switch( c ) { case 'h': usage_msg(stdout); exit(0); break; case 'd': cfg_delegated = 1; break; case 's': cfg_tx_size = atoi(optarg); break; case 'r': cfg_rx_size = atoi(optarg); break; case 'p': cfg_port = optarg; break; case '?': usage_err(); break; default: TEST(0); break; } argc -= optind; argv += optind; if( argc != 2 ) usage_err(); const char* interface = argv[0]; const char* server = argv[1]; struct client_state* cs = calloc(1, sizeof(*cs)); init(cs, interface, server, cfg_port); pthread_t tid; TEST( pthread_create(&tid, NULL, alarm_thread, cs) == 0 ); ev_loop(cs); return 0; }
int main(int argc, char *argv[]) { int s, idx; if (argc < 2 || strcmp(argv[1], "--help") == 0) usage_err("%s nsecs...\n", argv[0]); thread = calloc(argc-1, sizeof(*thread)); if (thread == NULL) err_exit("calloc"); for(idx = 0; idx < argc - 1; idx++) { thread[idx].sleep_time = get_int(argv[idx + 1], GN_NONNEG, NULL); thread[idx].state = TS_ALIVE; s = pthread_create(&thread[idx].tid, NULL, thread_func, &idx); if (s != 0) err_exit_en(s, "pthread_create"); } tot_threads = argc - 1; num_live = tot_threads; /* Join with terminated threads */ while(num_live > 0) { s = pthread_mutex_lock(&thread_mutex); if (s != 0) err_exit_en(s, "pthread_mutex_lock"); while (num_unjoined == 0) { s = pthread_cond_wait(&thread_died, &thread_mutex); if (s != 0) err_exit_en(s, "pthread_cond_wait"); } for (idx = 0; idx < tot_threads; idx++) { if (thread[idx].state == TS_TERMINATED) { s = pthread_join(thread[idx].tid, NULL); if (s != 0) err_exit_en(s, "pthread_join"); thread[idx].state = TS_JOINED; num_live--; num_unjoined--; printf("Reaped thread %d (numLived = %d)\n", idx, num_live); } } s = pthread_mutex_unlock(&thread_mutex); if (s != 0) err_exit_en(s, "pthread_mutex_unlock"); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { if (argc > 1 && strcmp(argv[1], "--help") == 0) usage_err("%s [dir...]\n", argv[0]); if (argc == 1) /* No arguments - use current directory */ list_files('.'); else for (argv++; *argv; argv++) list_files(*argv); err_exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int fd; struct iovec iov[3]; struct stat my_struct; int x; #define STR_SIZE 100 char str[STR_SIZE]; ssize_t num_read, tot_required; if (argc != 2 || strcmp(argv[1], "--help") == 0) usage_err("%s file\n", argv[0]); fd = open(argv[1], O_RDONLY); if (fd == -1) err_exit("open"); tot_required = 0; iov[0].iov_base = &my_struct; iov[0].iov_len = sizeof(struct stat); tot_required += iov[0].iov_len; iov[1].iov_base = &x; iov[1].iov_len = sizeof(x); tot_required += iov[1].iov_len; iov[2].iov_base = str; iov[2].iov_len = STR_SIZE; tot_required += iov_len[2].iov_len; num_read = readv(fd, iov, 3); if (num_read == -1) err_exit("readv"); if (num_read < tot_required) printf("Read fewer bytes than requested\n"); printf("total bytes requested: %ld; bytes read: %ld\n", (long)tot_required, (long)num_read); if (close(fd) == -1) err_exit("close file"); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int fd; struct iovec iov[3]; struct stat my_struct; /* first buffer */ int x; /* second buffer */ #define STR_SIZE 100 char str[STR_SIZE]; /* third buffer */ ssize_t num_read, tot_required; if (argc != 2 || strcmp(argv[1], "--help") == 0) usage_err("%s file\n", argv[0]); fd = open(argv[1], O_RDONLY); if (fd == -1) err_exit("open"); tot_required = 0; iov[0].iov_base = &my_struct; iov[0].iov_len = sizeof(struct stat); tot_required += iov[0].iov_len; iov[1].iov_base = &x; iov[1].iov_len = sizeof(int); tot_required += iov[1].iov_len; iov[2].iov_base = &str; iov[2].iov_len = STR_SIZE; tot_required += iov[2].iov_len; num_read = readv(fd, iov, 3); if (num_read == -1) err_exit("readv"); if (num_read < tot_required) printf("Fewer bytes read than requested\n"); printf("Total bytes requested: %ld, bytes read: %ld\n", tot_required, num_read); return EXIT_SUCCESS; }
int main (int argc, char **argv) { int argshift = 1; options opts; program_name = basename (argv[0]); scan_options (argc, argv, &opts); if (argc == 1) { usage_err(); }else { if (strstr(argv[1],STDIN_NAME) != NULL) { ++argshift; } char *target = argv[argshift]; ++argshift; if (argshift == argc) { match(stdin, STDIN_NAME, target, &opts, 0); } else { int filenum = argc - argshift; for (int argi = argshift; argi < argc; ++argi) { char *filename = argv[argi]; if (strcmp (filename, STDIN_NAME) == 0) { match(stdin, STDIN_NAME, target, &opts, 0); }else { FILE *input = fopen (filename, "r"); if (input != NULL) { match(input, filename, target, &opts, filenum); fclose (input); }else { exit_status = EXIT_FAILURE; fflush (NULL); fprintf (stderr, "%s: %s: %s\n", program_name, filename, strerror (errno)); fflush (NULL); } } } } } return exit_status; }
/* Changing the msg_qbytes setting of a System V message queue */ int main(int argc, char *argv[]) { struct msqid_ds ds; int msqid; if (argc != 3 || strcmp(argv[1], "--help") == 0) usage_err("%s msqid max-bytes\n", argv[0]); /* Retrive copy of associate data struct from kernel */ msqid = get_int(argv[1], 0, "msqid"); if (msgctrl(msqid, IPC_STAT, &ids) == -1) err_exit("msgctl"); d.msg_qbytes = get_int(argv[2], 0, "max-bytes"); /* Update associated data structure in kernel */ if (msgctl(msqid, IPC_SET, &ds) == -1) err_exit("msgctl"); exit(EXIT_SUCCESS); }
int main(int argc, char* argv[]) { struct rtt_options opts; opts.ping_frame_len = 42; opts.pong_frame_len = 42; opts.n_warm_ups = 10000; opts.n_iters = 100000; opts.inter_iter_gap_ns = 0; int c; while( (c = getopt(argc, argv, "i:w:f:g:h")) != -1 ) switch( c ) { case 'i': opts.n_iters = atoi(optarg); break; case 'w': opts.n_warm_ups = atoi(optarg); break; case 'f': opts.ping_frame_len = atoi(optarg); opts.pong_frame_len = atoi(optarg); break; case 'g': opts.inter_iter_gap_ns = atoi(optarg); break; case 'h': usage_msg(stdout); exit(0); break; case '?': usage_err(); default: RTT_TEST( 0 ); } argc -= optind; argv += optind; if( argc < 2 || argc > 3 ) usage_err(); const char* action = argv[0]; const char* tx_ep_spec = argv[1]; const char* rx_ep_spec = (argc >= 3) ? argv[2] : NULL; struct rtt_endpoint* tx_ep; if( spec_to_endpoint(&tx_ep, &opts, RTT_DIR_TX | ((rx_ep_spec) ? 0 : RTT_DIR_RX), tx_ep_spec) < 0 ) return 2; struct rtt_endpoint* rx_ep; if( rx_ep_spec != NULL ) { if( spec_to_endpoint(&rx_ep, &opts, RTT_DIR_RX, rx_ep_spec) < 0 ) return 3; } else { rx_ep = tx_ep; } if( ! strcmp(action, "ping") ) do_pinger(&opts, tx_ep, rx_ep); else if( ! strcmp(action, "pong") ) do_ponger(&opts, tx_ep, rx_ep); else usage_err(); do_cleanup(tx_ep, rx_ep); return 0; }
int main(int argc, char* argv[]) { int c; while( (c = getopt(argc, argv, "hr:n:i:w:sl:p:")) != -1 ) switch( c ) { case 'h': usage_msg(stdout); exit(0); break; case 'r': cfg_send_rate = atoi(optarg); break; case 'n': cfg_measure_nth = atoi(optarg); break; case 'i': cfg_iter = atoi(optarg); break; case 'w': cfg_warm_n = atoi(optarg); break; case 's': cfg_hw_ts = false; break; case 'l': cfg_log_level = atoi(optarg); break; case 'p': cfg_port = optarg; break; case '?': usage_err(); break; default: TEST(0); break; } argc -= optind; argv += optind; if( argc != 1 ) usage_err(); const char* mcast_intf = argv[0]; if( onload_is_present() ) { if( cfg_hw_ts ) { TRY( onload_stack_opt_set_int("EF_RX_TIMESTAMPING", 3) ); TRY( onload_stack_opt_set_int("EF_TX_TIMESTAMPING", 3) ); } } else if( cfg_hw_ts ) { fprintf(stderr, "ERROR: Cannot use hardware timestamp because Onload is " "not being used. You can use -s to use software timestamps, but " "they are much less accurate.\n"); exit(4); } else { msg(1, "Using software timestamps\n"); cfg_hw_ts = false; } struct server_state ss; init(&ss, mcast_intf); wait_for_client(&ss); event_loop(&ss); return 0; }
int main (int argc, char *argv[]) { // double legit; srand48(time(NULL)); // Seed RNG char *buffer = NULL; // A buffer for the received data long bufsize = 0; FILE* outfile; if (argc != 6) { printf("Arg count was %d.\n", argc); usage_err(); } // For statistical purposes int corrupt_count = 0; int loss_count = 0; int sockfd, portnum, bytes_recv, bytes_sent; int lost_packet = 0; socklen_t sin_size; struct sockaddr_in srv_addr; struct hostent *host; // Send data struct gbnpacket send_data; // Receive data struct gbnpacket recv_data; // recv_data.length = p_size(); // recv_data.sequence = 0; // Parse command line arguments host = (struct hostent *) gethostbyname(argv[1]); portnum = atoi(argv[2]); char* filename = argv[3]; printf("Filename is %s\n", filename); double p_loss = atof(argv[4]); // Probability of packet loss double p_corr = atof(argv[5]); // Probability of packet corruption sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) error_die("Error opening socket.\n"); // Initialize server address srv_addr.sin_family = AF_INET; srv_addr.sin_port = htons(portnum); srv_addr.sin_addr = *((struct in_addr *)host->h_addr); bzero(&(srv_addr.sin_zero),8); sin_size = sizeof(struct sockaddr); //------------------------------------ // SEND request for file //------------------------------------ memset(&send_data, 0, sizeof(struct gbnpacket)); send_data.type = REQUEST; send_data.sequence = 0; send_data.corrupt = 0; strcpy(send_data.data, filename); // Might have to \0 out the last byte of data...not sure yet // send_data.data[strlen(filename)] = '\0'; // send_data.length = p_header_size() + strlen(filename) + 1; // +1 for the null byte? send_data.length = strlen(filename); printf("Sending request to CS118 for %s\n", filename); long expecting_packet = 0; // The sequence number of the expected packet while (1) { if (send_data.type == REQUEST) { // Send // Convert to network byte order convertpacket_hton(&send_data); // bytes_sent = sendto(sockfd, &send_data, send_data.length, 0, bytes_sent = sendto(sockfd, &send_data, sizeof(struct gbnpacket), 0, (struct sockaddr *)&srv_addr, sizeof(struct sockaddr)); // TO-DO: Check to see if bytes_sent matches up with the length of the packet in total. // buffer = NULL; print_packet_info_client(&send_data, CLIENT); // printf("Request sent.\n"); } // -------------------------------- // RECEIVE data response // -------------------------------- printf("Waiting for response from CS118.\n"); // bytes_recv = recvfrom(sockfd, &recv_data, recv_data.length, 0, bytes_recv = recvfrom(sockfd, &recv_data, sizeof(struct gbnpacket), 0, (struct sockaddr*)&srv_addr, &sin_size); // Convert to host byte order convertpacket_ntoh(&recv_data); // Set packet lost or not lost_packet = play_the_odds(p_loss, &loss_count); if (lost_packet) { printf("\nLOST PACKET!\n\n"); continue; // Do nothing else, just receive the packet and move on. } // TO-DO: CHECK TO MAKE SURE THAT THE PROGRAM DOESN'T SEGFAULT IF recvfrom() FAILS! i.e. if bytesrecv == 0 // recv_data.data[bytes_recv] = '\0'; print_packet_info_client(&recv_data, SERVER); // printf("Received : %s\n", recv_data.data); // -------------------------------- // PREPARE acknowledgement // -------------------------------- if (recv_data.type == FIN) { // Send a FIN in return, and end the client process char *msg = "Terminating connection."; memset(&send_data, 0, sizeof(struct gbnpacket)); send_data.type = FIN; send_data.sequence = 0; send_data.corrupt = 0; // set_packet_corruption(); send_data.length = 0; // Don't need to initialize the data because of the memset printf("%s. Sending FIN packet.\n", msg); printf("STATS: Sent %d corrupt ACKs. Treated %d packets as \'lost\'.\n", corrupt_count, loss_count); // Convert to network byte order convertpacket_hton(&send_data); /* send_data.type = htonl(send_data.type); send_data.sequence = htonl(send_data.sequence); send_data.length = htonl(send_data.length); */ bytes_sent = sendto(sockfd, &send_data, sizeof(struct gbnpacket), 0, (struct sockaddr *)&srv_addr, sizeof(struct sockaddr)); // Modify the filename strcat(filename, ".received"); outfile = fopen(filename, "wb"); if (outfile) { fwrite(buffer, bufsize, 1, outfile); printf("Successfully wrote buffer to file \"%s\"\n.", filename); } else error_die("Error writing buffer to file."); return 0; // End the client process } if (!buffer) { bufsize = sizeof(char) * recv_data.total_length; buffer = (char *)malloc(bufsize); if (!buffer) error_die("Not enough space for client file buffer."); } memset(&send_data, 0, sizeof(struct gbnpacket)); send_data.type = ACK; // strcpy(send_data.data, "Acknowledged."); // send_data.data[strlen(send_data.data)] = '\0'; // Zero byte // send_data.length = p_header_size() + strlen(send_data.data) + 1; // Might need +1 for zero byte send_data.length = 0; // ACKs have no data // send_data.corrupt = 0; // send_data.corrupt = set_packet_corruption(p_corr); // ---------------------------------------------------------------- // SEND acknowledgement, depending on the last packet received. // ---------------------------------------------------------------- // Packet is legit if (recv_data.corrupt == 0 && recv_data.sequence <= expecting_packet) // Use <= for duplicate packets { // Copy file data into the buffer memcpy(buffer+recv_data.sequence, recv_data.data, recv_data.length); // send_data.sequence = recv_data.sequence + (bytes_recv - p_header_size()); send_data.sequence = recv_data.sequence + PACKETSIZE; send_data.corrupt = play_the_odds(p_corr, &corrupt_count); // Convert to network byte order /* send_data.type = htonl(send_data.type); send_data.sequence = htonl(send_data.sequence); send_data.length = htonl(send_data.length); */ // expecting_packet = recv_data.sequence + PACKETSIZE; expecting_packet = send_data.sequence; // Send // printf("Sending acknowledgement from else...\n"); // sendto(sockfd, &send_data, send_data.length, 0, // if (legit >= p_loss) // { // Convert to network byte order convertpacket_hton(&send_data); sendto(sockfd, &send_data, sizeof(struct gbnpacket), 0, (struct sockaddr *)&srv_addr, sizeof(struct sockaddr)); print_packet_info_client(&send_data, CLIENT); // } } // else if (recv_data.corrupt == 0 && recv_data.sequence < expecting_packet) // { // printf("\nDUPLICATE PACKET, IGNORING!\n\n"); // continue; // DUPLICATE PACKET // } // if (recv_data.sequence != expecting_packet || recv_data.corrupt == 1) // Packet received OUT OF ORDER or is CORRUPT else // Packet is not legit { // Be sure to send duplicate ACKs? Not in the book // The ACK should be for the last correctly-received packet. send_data.sequence = expecting_packet; send_data.corrupt = play_the_odds(p_corr, &corrupt_count); // Send // printf("Sending acknowledgement from if...\n"); // sendto(sockfd, &send_data, send_data.length, 0, // if (legit >= p_loss) // { // Convert to network byte order /* send_data.type = htonl(send_data.type); send_data.sequence = htonl(send_data.sequence); send_data.length = htonl(send_data.length); send_data.corrupt = htonl(send_data.corrupt); */ convertpacket_hton(&send_data); sendto(sockfd, &send_data, sizeof(struct gbnpacket), 0, (struct sockaddr *)&srv_addr, sizeof(struct sockaddr)); print_packet_info_client(&send_data, CLIENT); // } } } return 0; }