Skip to content

Instantly share code, notes, and snippets.

@kkumar-fk
Last active July 23, 2019 04:32
Show Gist options
  • Save kkumar-fk/d2c845c5eae608d432888daa4112f6ea to your computer and use it in GitHub Desktop.
Save kkumar-fk/d2c845c5eae608d432888daa4112f6ea to your computer and use it in GitHub Desktop.
Program to benchmark client
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <sys/wait.h>
#include <netdb.h>
void create_children(int nprocs, int parent_pid)
{
while (nprocs-- > 0) {
if (getpid() == parent_pid && fork() < 0)
exit(1);
}
}
int main(int argc, char *argv[])
{
int fd, count, nprocs, parent_pid = getpid();
struct sockaddr_in server;
struct hostent *server_ent;
const struct linger nolinger = { .l_onoff = 1, .l_linger = 0 };
if (argc != 5) {
fprintf(stderr, "Server-IP Port# #Processes #Conns_per_Proc\n");
return 1;
}
nprocs = atoi(argv[3]);
count = atoi(argv[4]);
if ((server_ent = gethostbyname(argv[1])) == NULL) {
perror("gethostbyname");
return 1;
}
bzero((char *)&server, sizeof server);
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2]));
bcopy((char *)server_ent->h_addr, (char *)&server.sin_addr.s_addr,
server_ent->h_length);
create_children(nprocs, parent_pid);
if (getpid() == parent_pid) {
/* Parent does nothing other than wait for children */
while (wait(NULL) != -1);
} else {
/* while the children connect() ‘count’ times to the server */
while (count-- > 0) {
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
return 1;
}
if (connect(fd, (struct sockaddr *)&server, sizeof server) < 0) {
perror("connect");
return 1;
}
/* Reset connection to avoid TIME-WAIT state */
setsockopt(fd, SOL_SOCKET, SO_LINGER, &nolinger, sizeof nolinger);
close(fd);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment