Optimize code (replace printf with write, malloc with alloca)
1 parent 1784c32 commit 7f159ef5c78d4724db903f55dbb2b0320e0caf71
@Andreas Jaggi Andreas Jaggi authored on 10 Aug 2006
Showing 4 changed files
View
3
■■
c/rexec/Makefile
$(CC) $(CFLAGS) $^ -o rexec
rexecd: rexecd.c rexec.h
$(CC) $(CFLAGS) $^ -o rexecd
 
clean:
rm -f rexec rexecd
View
48
c/rexec/rexec.c
*/
 
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <errno.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
 
#include "rexec.h"
 
const char versionmsg[] = "rexec 0.2\n";
 
void usage(void);
void version(void);
void license(void);
 
int main ( int argc, char* argv[] ) {
int localargsparsed = 0;
int i;
int sock;
int tmp;
int child;
char buff;
char *command = NULL;
in_addr_t remote_addr = 0;
struct sockaddr_in *remote_host_addr = NULL;
usage();
exit(-1);
}
 
remote_host_addr = malloc(sizeof(struct sockaddr_in));
remote_host_addr = alloca(sizeof(struct sockaddr_in));
remote_host_addr->sin_family = AF_INET;
remote_host_addr->sin_addr.s_addr = remote_addr;
remote_host_addr->sin_port = REXEC_PORT;
 
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if ( sock < 0 ) {
printf("error: %s\n", strerror(errno));
showerror("socket");
exit(-1);
}
 
tmp = connect(sock, (struct sockaddr*)remote_host_addr, sizeof(struct sockaddr_in));
free(remote_host_addr);
if ( tmp < 0 ) {
printf("error: %s\n", strerror(errno));
if ( connect(sock, (struct sockaddr*)remote_host_addr, sizeof(struct sockaddr_in)) < 0 ) {
showerror("connect");
exit(-1);
}
 
/* send command with args and a final \n */
write(sock, argv[i], strlen(argv[i])+1);
}
write(sock, "\n", 1);
 
if ( (child = fork()) == 0 ) {
 
if ( fork() == 0 ) {
while ( tmp > -1 ) {
if ( (tmp = read(sock, &buff, 1)) == 1 ) {
printf("%c", buff);
write(1, &buff, 1);
} else {
usleep(200000);
}
}
} else {
while ( feof(stdin) == 0 ) {
if ( buff = (char)getchar() ) {
while ( tmp > -1 ) {
if ( (tmp = read(1, &buff, 1)) == 1 ) {
write(sock, &buff, 1);
} else {
usleep(200000);
}
}
}
 
tmp = shutdown(sock, SHUT_RDWR);
if ( tmp < 0 ) {
printf("error: %s\n", strerror(errno));
 
if ( shutdown(sock, SHUT_RDWR) < 0 ) {
showerror("shutdown");
exit(-1);
}
 
tmp = close(sock);
if ( tmp < 0 ) {
printf("error: %s\n", strerror(errno));
if ( close(sock) < 0 ) {
showerror("close");
exit(-1);
}
 
while ( wait(&tmp) > 0 ) { }
exit(0);
}
 
void usage(void) {
fprintf(stdout, "%s", usagemsg);
write(1, usagemsg, strlen(usagemsg));
}
 
void version(void) {
fprintf(stdout, "%s", versionmsg);
write(1, versionmsg, strlen(versionmsg));
}
void license(void) {
fprintf(stdout, "%s", licensemsg);
}
View
c/rexec/rexec.h
View
c/rexec/rexecd.c