ΟΚ!
In fact the file is not an argument (I said not to confuse you) ............. i read file name from tcp socket()....
server runs normally and make wc.txt but nothing saved inside....
here is my server code:
Code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <unistd.h>
// communicates with each client...
void dostuff(int);
// print errors....
void error(char *msg)
{
perror(msg);
exit(1);
}
main()
{
int sockfd, newsockfd, portno, clilen, pid;
struct sockaddr_in cli_addr,serv_addr;
// make socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
//default times for tcp
bzero((char *) &serv_addr, sizeof(serv_addr));
portno=atoi("50006");
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(portno);
//bind for requests
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR on binding");
// call listen()
listen(sockfd,5);
clilen = sizeof(cli_addr);
//do accept as many requests have portno = 50006 and make childs to serve them...
// while loop run continuously ---server never stops
while (1) {
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
pid = fork();
if (pid < 0)
error("ERROR on fork");
// in child proc ,call function do stuff
if (pid == 0) {
close(sockfd);
dostuff(newsockfd);
exit(0);
}
else{
wait(0);
close(newsockfd);
}
} /* end of while */
return 0; /* we never get here */
}
void dostuff (int sock)
{
int n;
char buffer[256];
char message[256];
bzero(buffer,256);
// read from socket
n = read(sock,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s (from client) \n",buffer);
//check if given file exists...
char *temp=(char*)malloc(100);
sprintf(temp,"ls %s",buffer);
if(system((char *)temp)!=0){
strcpy(message,"no such file or directory");
free(temp);
if (write(sock,message,sizeof(message))< 0) error("ERROR writing to socket");
}
free(temp);
//count number of words in given file
char *temp2=(char*)malloc(200);
sprintf(temp2,"wc -w %s >wc.txt",buffer);//redirect output to wc.txt
system((char *)temp2);
free(temp2);
}