This program uses pipes to pass messages between processes. I compile with
gcc -Wall -o p2 p2.c INIT.DAT LOG.DAT TRANS1 TRANS2
I keep getting this error after compilation:
/usr/bin/ld:INIT.DAT: file format not recognized; treating as linker script
/usr/bin/ld:INIT.DAT:1: syntax error
with this source code:
#include "my.h"
int main(int argc, char **argv)
{
int pipe1[2], pipe2[2], pipe3[2];
int pid[3];
int p;
int len, i, index, check, oneOrTwo;
char val[10];
char buff[MAXLINE];
char strLog[MAXLINE];
char* token;
FILE *log, *trans1, *trans2, *init;
//Create pipes
p = pipe(pipe1);
if(p < 0)
{
printf("pipe error");
exit(0);
}
else
printf("successful pipe1 = %d\n", p);
p = pipe(pipe2);
if(p < 0)
{
printf("pipe error");
exit(0);
}
else
printf("successful pipe2 = %d\n", p);
p = pipe(pipe3);
if(p < 0)
{
printf("pipe error");
exit(0);
}
else
printf("successful pipe3 = %d\n", p);
//Store Manager
pid[0] = fork();
if(pid[0] == 0)
{
//Close unused channels
if(close(pipe1[1]) == -1)
printf("close error closing pipe1[1]\n");
if(close(pipe2[0]) == -1)
printf("close error closing pipe2[0]\n");
if(close(pipe3[0]) == -1)
printf("close error closing pipe3[0]\n");
//open INI.DAT
init = fopen(argv[1], "r");
if(init == NULL)
{
printf("INIT.DAT failed to open");
exit(0);
}
len = 0;
//Gets TABLE size
while(fgets(buff, MAXLINE, init) != NULL)
len++;
struct TABLE table[len];
i = 0;
init = fopen(argv[1], "r");
//Fills table
while(fgets(buff, MAXLINE, init) != NULL)
{
//id
token = strtok(buff, " ");
strcpy(table[i].id, token);
//value
token = strtok(NULL, " ");
table[i].value = atoi(token);
i++;
}
//Opens LOG.DAT
log = fopen(argv[2], "r+");
if(log == NULL)
{
printf("LOG.DAT failed to open");
exit(0);
}
//Send and receive messages
while(1)
{
check = 0;
//Quit when pipe is closed
if(read(pipe1[0], buff, MAXLINE) == -1)
break;
strcpy(strLog, "Store Manager received message: ");
strcat(strLog, buff);
fwrite(strLog, 1, sizeof(strLog), log);
//1 or 2
token = strtok(buff, " ");
oneOrTwo = atoi(token);
//pid
token = strtok(NULL, " ");
//U
token = strtok(NULL, " ");
//Update
if(strcmp(token, "U") == 0)
{
//id
token = strtok(NULL, " ");
for(i = 0; i < len; i++)
{
if(token == table[i].id)
{
check = 1;
index = i;
//value
token = strtok(NULL, " ");
table[i].value += atoi(token);
}
}
//Update failed
if(check == 0)
{
strcpy(strLog, "Store Manager sent message: Error updating table");
fwrite(strLog, 1, sizeof(strLog), log);
if(oneOrTwo == 1)
write(pipe2[1], "Error updating table", MAXLINE);
else
write(pipe3[1], "Error updating table", MAXLINE);
}
//Update succeeded
else
{
strcpy(strLog, "Store Manager sent message: U 0 ");
strcat(strLog, table[index].id);
strcat(strLog, " ");
sprintf(val, "%d", table[index].value);
strcat(strLog, val);
fwrite(strLog, 1, sizeof(strLog), log);
if(oneOrTwo == 1)
write(pipe2[1], strLog, MAXLINE);
else
write(pipe3[1], strLog, MAXLINE);
}
}
//Read
else
{
check = 0;
for(i = 0; i < len; i++)
{
//Read succeeded
if(token == table[i].id)
{
check = 1;
strcpy(strLog, "Store Manager sent message: R ");
sprintf(val, "%d", oneOrTwo);
strcat(strLog, val);
strcat(strLog, " ");
strcat(strLog, table[i].id);
strcat(strLog, " 0");
fwrite(strLog, 1, sizeof(strLog), log);
if(oneOrTwo == 1)
write(pipe2[1], strLog, MAXLINE);
else
write(pipe3[1], strLog, MAXLINE);
}
}
//Read failed
if(check == 0)
{
strcpy(strLog, "Store Manager sent message: Error reading table");
fwrite(strLog, 1, sizeof(strLog), log);
if(oneOrTwo == 1)
write(pipe2[1], "Error reading table", MAXLINE);
else
write(pipe3[1], "Error updareadingting table", MAXLINE);
}
}
}
//Close files and quit process
fclose(init);
fclose(log);
exit(0);
}
//P1
pid[1] = fork();
if(pid[1] == 0)
{
//Close unused channels
if(close(pipe1[0]) == -1)
printf("close error closing pipe1[0]\n");
if(close(pipe2[1]) == -1)
printf("close error closing pipe2[1]\n");
//Open LOG.DAT
log = fopen(argv[2], "r+");
if(log == NULL)
{
printf("LOG.DAT failed to open");
exit(0);
}
//Open TRANS1
trans1 = fopen(argv[3], "r");
if(log == NULL)
{
printf("LOG.DAT failed to open");
exit(0);
}
//Send and receive messages
while(fgets(buff, MAXLINE, trans1) != NULL)
{
strcpy(strLog, "Process 1 sent message: ");
strcat(strLog, buff);
fwrite(strLog, 1, sizeof(strLog), log);
write(pipe1[1], buff, MAXLINE);
read(pipe2[0], buff, MAXLINE);
strcpy(strLog, "Process 1 received message: ");
strcat(strLog, buff);
fwrite(strLog, 1, sizeof(strLog), log);
sleep(3);
}
//Close files and quit process
fclose(trans1);
fclose(log);
exit(0);
}
//P2
pid[2] = fork();
if(pid[2] == 0)
{
//Close unused channels
if(close(pipe1[0]) == -1)
printf("close error closing pipe1[0]\n");
if(close(pipe3[1]) == -1)
printf("close error closing pipe3[1]\n");
//Open LOG.DAT
log = fopen(argv[2], "r+");
if(log == NULL)
{
printf("LOG.DAT failed to open");
exit(0);
}
//Open TRANS2
trans2 = fopen(argv[4], "r");
if(log == NULL)
{
printf("LOG.DAT failed to open");
exit(0);
}
//Send and receive messages
while(fgets(buff, MAXLINE, trans1) != NULL)
{
strcpy(strLog, "Process 1 sent message: ");
strcat(strLog, buff);
fwrite(strLog, 1, sizeof(strLog), log);
write(pipe1[1], buff, MAXLINE);
read(pipe3[0], buff, MAXLINE);
strcpy(strLog, "Process 1 received message: ");
strcat(strLog, buff);
fwrite(strLog, 1, sizeof(strLog), log);
sleep(3);
}
//Close files and quit process
fclose(trans2);
fclose(log);
exit(0);
}
//Wait for processes to quit
for(i = 0; i < 3; i ++)
{
if(waitpid(pid[i], NULL, 0) == -1)
{
printf("waitpid error");
exit(0);
}
}
}
with these input files:
I
(NOT IN FILE) INIT.DAT
DISNEY 3
INTEL 56
Hate
(NOT IN FILE) TRANS1
R XXXX
R DISNEY
This
(NOT IN FILE) TRANS2
R INTEL
U INTEL 45
U DISNEY 21
U DISNEY 21
R DISNEY
U DISNEY 21
U DIY 21
Formatting
LOG.DAT is empty.
I have no idea why I'm getting this error, because even if I change INIT.DAT to INIT.txt or any other file format, it still doesn't work. It has to be an issue with my code, but I can't see it.
Thanks.
Related
so i am trying to implement a TCP server-client(s) using server ip and port. Connection between the two was established, with the use of threads.
Now i'm expecting the program to: for everytime a client joins or leave, if there are other clients present, then it will print "Client has joined/left the server" on these other clients screen. However if it is the only client present, it won't say the join or leave stuff and will proceed with asking user an input of what does the client wants to do.(user input is what the client has typed after this arrow ">")
What it is actually doing: When the first client has successfully joined the server, the command line remains empty, the ">" does not appear and even if you can type, no input is recorded by the client. As you connect a second client, that's when the arrow appears on the first client only and you can start inputting.
I would like to know which part i should edit to make my client when alone to start taking input without needing another client to join before doing so + When there are multiple clients and a client joins/leave, on the other clients' screen is printed "Client has joined/left the server"
Server code
void client_queuing(client_thr *cl){
pthread_mutex_lock(&cli_mutex);
for(int i=0; i < MAXLINE; ++i){
if(!cli[i]){
cli[i] = cl;
break;
}
}
pthread_mutex_unlock(&cli_mutex);
}
void client_removal(int uid){
pthread_mutex_lock(&cli_mutex);
for(int i=0; i < MAXLINE; ++i){
if(cli[i]){
if(cli[i]->uid == uid){
cli[i] = NULL;
break;
}
}
}
pthread_mutex_unlock(&cli_mutex);
}
void convey_msg(char *st, int uid){
pthread_mutex_lock(&cli_mutex);
for(int i=0; i<MAXLINE; ++i){
if(cli[i]){
if(cli[i]->uid != uid){
if(write(cli[i]->sockfd, st, strlen(st)) < 0){
perror("ERROR: Failure to write to descriptor");
break;
}
}
}
}
pthread_mutex_unlock(&cli_mutex);
}
void *man_cli(void *arg){
char buffer_o[SIZEOF_BUFFER];
char nickname[20];
int leave_flag = 0;
num_client++;
client_thr *clice = (client_thr *)arg;
// nickname
if(recv(clice->sockfd, nickname, 20, 0) <= 0 || strlen(nickname) >= 19){
printf("Name not Entered.\n");
leave_flag = 1;
}
else{
strcpy(cli->nickname, nickname);
sprintf(buffer_o, "A new user %s has joined SNC!\n", cli->nickname);
printf("%s", buffer_o);
convey_msg(buffer_o, clice->uid);
}
bzero(buffer_o, SIZEOF_BUFFER);
while(1){
if (leave_flag) {
break;
}
int receive = recv(clice->sockfd, buffer_o, SIZEOF_BUFFER, 0);
if (receive > 0){
if(strlen(buffer_o) > 0){
convey_msg(buffer_o, clice->uid);
array_trimming(buffer_o, strlen(buffer_o));
printf("%s -> %s\n", buffer_o, clice->nickname);
//printf("%s\n", buffer_o);
}
}
else if (receive == 0 || strcmp(buffer_o, "quit") == 0){
sprintf(buffer_o, "Server: %s has stopped chatting.\n", clice->nickname);
printf("%s", buffer_o);
convey_msg(buffer_o, clice->uid);
//trial
//strcpy(buffer_o, clice->nickname);
send(clice->sockfd, buffer_o, strlen(buffer_o)+1,0);
leave_flag = 1;
}
/* else {
printf("Error is -1\n");
leave_flag = 1;
} */
bzero(buffer_o, SIZEOF_BUFFER);
}
/* Delete client from queue and yield thread */
close(clice->sockfd);
client_removal(clice->uid);
free(clice);
num_client--;
pthread_detach(pthread_self());
return NULL;
}
client code
void handle_message_convey() {
char message[LENGTH] = {};
char buff[LENGTH + 20] = {};
while(1) {
flush_stdout();
fgets(message, LENGTH, stdin);
array_trimming(message, LENGTH);
if (strcmp(message, "quit") == 0) {
break;
}
else {
sprintf(buff, "%s: %s\n", nickname, message);
send(sockfd, buffer, strlen(buff), 0);
}
bzero(message, LENGTH);
bzero(buffer, LENGTH + 20);
}
quit_with_catch_ctrl_c(2);
}
void handle_message_recv() {
char message[LENGTH] = {};
while (1) {
int message_rcv = recv(sockfd, message, LEN, 0);
if (message_rcv > 0) {
printf("%s", message);
flush_stdout();
}
else if (message_rcv == 0) {
break;
}
else {
// nothing happens = -1
}
memset(message, 0, sizeof(message));
}
}
int main(){
recv(sock_fd, buffer_o, sizeof(buffer_o), 0);
//printf("%s \n", buffer_o);
pthread_t message_sending_thr;
if(pthread_create(&message_sending_thr, NULL, (void* ) handle_message_convey, NULL) != 0) {
printf("Error with pthread:");
}
//printf("Hello, Welcome!");
pthread_t message_del_thr;
if(pthread_create(&message_del_thr, NULL, (void *)handle_message_recv, NULL) != 0){
printf("Error with pthread");
}
}
I'm trying to create a chatroom. I have a server that takes commands and does things with them and I have client that sends them. Im using poll to monitor multiple clients. Whenever my client sends a command with the arguments it reads that line and gets some characters from the following line in client.
client(relevant code):
char *data = "REGISTER Johndoe pass1ds3";
send(sockfd,data, strlen(data), 0);
char *data3= "LOGIN Johndoe pass1ds3";
send(sockfd,data3, strlen(data3), 0);
//The server would get "REGISTER Johndoe pass1ds3LOGIN" instead of "REGISTER Johndoe pass1ds3".
server(relevant par):
for (int i = 1; i < (numfds + 1); i++){
if(pollfds[i].revents & POLLRDNORM){
if (readCmd(&pollfds[i], pollfds[i].fd, users,cmdBuf, 32) == -1)
printf("Connection closed\n");
else if(readCmd(&pollfds[i], pollfds[i].fd, users ,cmdBuf, 32) == -2)
printf("Error with recv");
}
}
readCmd(the command that reads from client):
int readCmd(struct pollfd * pollInfo, int sockfd, struct user *users,char* buf, int bufSize){
int num = recv(sockfd , buf, bufSize, 0);
if( num == -1)
return -2;
else if (num == 0 || (num < 0 && errno == ECONNRESET)){
// printf("Nothing to read\n");
close(sockfd);
return -1;
}
else{
printf("recieved %d bytes\n", num);
buf[num] = '\0';
char tokenList[5][30];
char* context = NULL;
char* token = strtok_r(buf, " ", &context);
// Parse command and arguments
int ite = 0;
while (token != NULL) {
strcpy(tokenList[ite], token);
ite++;
token = strtok_r(NULL, " ", &context);
}
if(strcmp(tokenList[0], "REGISTER") == 0){
registerAcc(tokenList[1], tokenList[2]);
}
else if (strcmp(tokenList[0], "LOGIN") == 0){
login(tokenList[1], tokenList[2], users);
}
}
return 0;
}
I am trying to implement an ssh client using libssh but output seems to just be an echo of whatever been sent main part of program is :
do {
printf("Enter Command or q to exit: ");
fgets(command, 100, stdin);
command[strlen(command)-1] = 0;
if (ssh_channel_write(channel, command, strlen(command)) != strlen(command)) {
fprintf(stderr, "Unable to execute command\n");
exit(1);
}
printf("Data Sent: %s\n", command);
sleep(1);
while ((bytes_recieved = ssh_channel_read_nonblocking(channel, output, 2024, 0))) {
if (bytes_recieved < 1) {
fprintf(stderr, "Error Reading Output or End Of Data\n");
break;
}
printf("Data Recieved(%d): %.*s\n", bytes_recieved, bytes_recieved, output);
}
}while (strcmp(command, "q")!=0 ||strcmp(command, "Q")!=0 );
first command result in what I guess the banner to be sent althought I guess the banner is supposed to be sent before connection , this is output for only the first command after that anything i type is just echod back.
Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.4.0-40-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
* "If you've been waiting for the perfect Kubernetes dev solution for
macOS, the wait is over. Learn how to install Microk8s on macOS."
https://www.techrepublic.com/article/how-to-install-microk8s-on-macos/
65 updates can be installed immediately.
0 of these updates are security updates.
To see these additional updates run: apt list --upgradable
Your Hardware Enablement Stack (HWE) is supported until April 2025.
sshd_config files (server side) have been edited to include this as highlights:
AllowTcpForwarding no
PasswordAuthentication yes
PermitRootLogin prohibit-password
AllowUsers user_name
Whole code is here for anyone if he want's to use or test on it just change your username in ssh_options_set( ) part of the code.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <libssh/libssh.h>
int main(int argc, char* argv[])
{
printf("libssh version: %s\n", ssh_version(0));
if (argc < 2){
fprintf(stderr, "USAGE command hostname\n");
exit(1);
}
char* hostname = argv[1];
int port = 22;
ssh_session ssh = ssh_new();
ssh_options_set(ssh, SSH_OPTIONS_HOST, hostname);
ssh_options_set(ssh, SSH_OPTIONS_PORT, &port);
// TODO: Enable it in the future
int verbosity = SSH_LOG_PROTOCOL;
ssh_options_set(ssh, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
int error_code = ssh_connect(ssh);
if (error_code != SSH_OK){
fprintf(stderr, "Error creating connection with error %d", error_code);
exit(1);
}
printf("Connected to %s on port %d.\n", hostname, port);
printf("banner %s\n", ssh_get_serverbanner(ssh));
ssh_key key;
if(ssh_get_server_publickey(ssh, &key) != SSH_OK) {
fprintf(stderr,"Couldnt get server key\n");
exit(1);
}
unsigned char* hash;
size_t hash_len;
if(ssh_get_publickey_hash(key, SSH_PUBLICKEY_HASH_SHA1, &hash, &hash_len)!=SSH_OK){
fprintf(stderr, "Error Calculating Hash\n");
exit(1);
}
printf("Host public key hash:\n");
ssh_print_hash(SSH_PUBLICKEY_HASH_SHA1, hash, hash_len);
ssh_key_free(key);
ssh_clean_pubkey_hash(&hash);
enum ssh_known_hosts_e known = ssh_session_is_known_server(ssh);
switch (known) {
case SSH_KNOWN_HOSTS_OK:printf("known Host\n");break;
case SSH_KNOWN_HOSTS_NOT_FOUND:printf("no host file\n");break;
case SSH_KNOWN_HOSTS_CHANGED:printf("Host Changed\n");break;
case SSH_KNOWN_HOSTS_ERROR:
printf("Host error. %s\n", ssh_get_error(ssh)); return 1;
case SSH_KNOWN_HOSTS_UNKNOWN: printf("Unknown Host verify please\n");break;
}
if(known == SSH_KNOWN_HOSTS_CHANGED){
printf("Server key changed Exiting\n");
exit(1);
}
if (
known == SSH_KNOWN_HOSTS_OTHER ||
known == SSH_KNOWN_HOSTS_UNKNOWN ||
known == SSH_KNOWN_HOSTS_NOT_FOUND)
{
printf("Do you want to trust this host\n");
char answer[10];
fgets(answer, 10, stdin);
if(answer[0] == 'y' || answer[0] == 'Y'){
ssh_session_update_known_hosts(ssh);
}else{
printf("Not trusting it\n");
exit(1);
}
}
ssh_options_set(ssh, SSH_OPTIONS_USER, "my_user");
printf("Enter password: ");
char pass[20];
fgets(pass, 20, stdin);
pass[strlen(pass)-1] = 0 ;
if(ssh_userauth_password(ssh, 0, pass) != SSH_AUTH_SUCCESS){
fprintf(stderr, "Unable to Authentication\n");
exit(1);
}else {
printf("Authentication successful!\n");
}
int err = ssh_userauth_publickey_auto(ssh, NULL, NULL);
if (err == SSH_AUTH_ERROR){
fprintf(stderr, "Unable to Authunticate\n");
exit(1);
}
ssh_channel channel = ssh_channel_new(ssh);
if(!channel){
fprintf(stderr, "Couldnt create a channel\n");
exit(1);
}
if(ssh_channel_open_session(channel) != SSH_OK){
fprintf(stderr, "Error Openning Session\n");
exit(1);
}
if (ssh_channel_request_pty(channel) != SSH_OK){
fprintf(stderr, "Can't initiate terminal\n");
exit(1);
}
if(ssh_channel_change_pty_size(channel, 80, 400) != SSH_OK){
fprintf(stderr, "Error Changing size of terminal\n");
exit(1);
}
if(ssh_channel_request_shell(channel) != SSH_OK){
fprintf(stderr, "Couldn't request a shell\n");
exit(1);
}
char command[100];
char output[2024];
int bytes_recieved;
do {
printf("Enter Command or q to exit: ");
fgets(command, 100, stdin);
command[strlen(command)-1] = 0;
if (ssh_channel_write(channel, command, strlen(command)) != strlen(command)) {
fprintf(stderr, "Unable to execute command\n");
exit(1);
}
printf("Data Sent: %s\n", command);
sleep(1);
while ((bytes_recieved = ssh_channel_read_nonblocking(channel, output, 2024, 0))) {
if (bytes_recieved < 1) {
fprintf(stderr, "Error Reading Output or End Of Data\n");
break;
}
printf("Data Recieved(%d): %.*s\n", bytes_recieved, bytes_recieved, output);
}
}while (strcmp(command, "q")!=0 ||strcmp(command, "Q")!=0 );
ssh_channel_send_eof(channel);
ssh_channel_close(channel);
ssh_channel_free(channel);
ssh_disconnect(ssh);
ssh_free(ssh);
return 0;
}
Its the 1st time im making a question here , so i hope im not making any mistakes...
Im doing a server-client program and i have this error when i run client, i have "core dumped error".
I think i know where is the error but i dont know how to solve it.
I have 2 structs :
typedef struct {
int pid;
int cmd; //1 -login,2-registrar,3-tecla
char login[100];
char pw[100];
int tecla;
} PEDIDO;
typedef struct {
int cmd;
int res;
BONECO *b;
} RESPOSTA;
Code when server sends data to client through a named pipe :
int main(int argc, char *argv[], char *envp[]){
//...
i = read(fd, &p, sizeof (p));
printf(">>> Li %d bytes\n", i);
printf("User : %s PID : %d\n", p.login, p.pid);
if (p.cmd == 1) { //LOGIN
char user_fd[100], pw_fd[100];
FILE *f = fopen(argv[1], "r");
if (!f) {
printf("Erro ao abrir ficheiro\n");
exit(0);
}
while ((fscanf(f, "%s %s ", user_fd, pw_fd))) {
if (strcmp(p.login, user_fd) == 0 && strcmp(p.pw,pw_fd) == 0) {
printf("\nLOGIN CORRECTO!!!\n");
for (i = 0; i < 20; i++) {
if (clientes[i][0] != p.pid && clientes[i][0] == -1) {
clientes[i][0] = p.pid;
break;
}
}
sprintf(cli_fifo, "ccc%d", p.pid);
fd_resp = open(cli_fifo, O_WRONLY);
r.cmd = 1;
r.res = 1;
i = write(fd_resp, &r, sizeof (r));
close(fd_resp);
fclose(f);
break;
}
//...
}
Code of client to receive data from server :
void *recebe_msg(void *dados) {
int i;
sprintf(cli_fifo, "ccc%d", getpid());
mkfifo(cli_fifo, 0600);
fd_resp = open(cli_fifo, O_RDWR);
menu();
do {
i = read(fd_resp, &r, sizeof (r));
if (ESTADO == 0) {
if (r.cmd == 1 && r.res == 1) { // OK
ESTADO = 1;
wclear(win);
mvwprintw(win, 10, 14, "Login efectuado com sucesso!");
wprintw(win, "BONECO %d, %d , %d , %d ",r.b[0].num,r.b[0].humano,r.b[0].remate,r.b[0].tempo);
wrefresh(win);
sleep(3);
desenha_campo();
}
if (r.cmd == 1 && r.res == 0) { // NOK
wclear(win);
mvwprintw(win, 10, 14, "Senha e/ou login incorrectos!!!");
wrefresh(win);
sleep(3);
menu();
}
if (r.cmd == 2 && r.res == 0) {
wclear(win);
mvwprintw(win, 10, 14, "Login já está em uso!");
wrefresh(win);
sleep(3);
menu();
}
if (r.cmd == 2 && r.res == 1) {
wclear(win);
mvwprintw(win, 10, 14, "Registo efectuado com sucesso!");
wrefresh(win);
sleep(3);
menu();
}
if (r.cmd == 9) { // sair
FIM = 1;
}
} else if (ESTADO == 1 || ESTADO == 2) {
wclear(win3);
scrollok(win3, TRUE);
keypad(win3, TRUE);
noecho();
if (r.cmd == 3) { // actualizacao de jogadores
desenha_campo();
desenha_jogadores();
} else if (r.cmd == 9) { // sair
FIM = 1;
}
}
} while (!FIM);
close(fd_resp);
unlink(cli_fifo);
pthread_exit(0);
}
OBS: I think the error is on the 3rd field of struct RESPOSTA, but i dont know how to solve it
Here you read BONECO structure:
i = read(fd_resp, &r, sizeof (r));
Please note, BONECO is declared as pointer, NOT ACTUAL DATA.
But here you try to read this data:
wprintw(win, "BONECO %d, %d , %d , %d ",r.b[0].num,r.b[0].humano,r.b[0].remate,r.b[0].tempo);
While you try to access r.b[0], you get segmentation fault, as you try to dereference b pointer, which point to... Unknown location. This cause error just as planned.
I suggest to modify your struct to:
typedef struct {
int cmd;
int res;
int count_of_boneco;
BONECO b[];
} RESPOSTA;
If you allocate sufficiently large buffer, you can read all your data and then dereference at you do it now.
The below code works fine for smaller files where the last packet contains data less than maximum length, the function exit properly by displaying file received.
How ever if the last packet or buffer of file being transmitted contains exact number as the size of receiving buffer array 512 in my case. then th program keeps waiting for next packet.
All files with size multiple of 512 in my case stuck.
Below is the code:
CLIENT code for receiving:
void receiveFile() {
printf("inside receiveFile method\n");
char* fr_name = "final.txt";
int i;
FILE *fr = fopen(fr_name, "a");
int LENGTH = 512;
int fileLength=0;
char revbuf[LENGTH];
if (fr == NULL) {
printf("File %s Cannot be opened.\n", fr_name);
} else {
printf("starting to write the file\n");
bzero(revbuf, LENGTH);
int fr_block_sz = 0;
i=0;
while ((fr_block_sz = recv(4, revbuf, LENGTH, 0)) > 0) {
fileLength+=fr_block_sz;
i++;
printf("Received buffer: %d, %d\n",fr_block_sz,i);
int write_sz = fwrite(revbuf, sizeof(char), fr_block_sz, fr);
if (write_sz < fr_block_sz) {
error("File write failed.\n");
}
bzero(revbuf, LENGTH);
if (fr_block_sz == 0 || fr_block_sz != 512) {
break;
}
}
if (fr_block_sz < 0) {
if (errno == EAGAIN) {
printf("recv() timed out.\n");
} else {
fprintf(stderr, "recv() failed due to errno = %d\n", errno);
}
}
printf("FILE RECEIVED....Total Bytes received:%d \n",fileLength);
}
fclose(fr);
}
Server for Receiving the file:
void sendFile() {
printf("inside sendFile method\n");
char* fs_name = "mb.txt";
int LENGTH = 512;
int sfileLength=0;
char sdbuf[LENGTH];
int i=0;
printf("[Client] Sending %s to the Server... \n", fs_name);
FILE *fs = fopen(fs_name , "r");
if (fs == NULL) {
perror("ERROR: File not found.\n");
exit(1);
}
bzero(sdbuf, LENGTH);
int fs_block_sz;
while ((fs_block_sz = fread(sdbuf, sizeof(char), LENGTH, fs)) > 0) {
i++;
printf("Sent:%d , %d \n", fs_block_sz,i);
sfileLength+=fs_block_sz;
if (send(4, sdbuf, fs_block_sz, 0) < 0) {
fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n",
fs_name, errno);
break;
}
bzero(sdbuf, LENGTH);
}
printf("File sent.... Total Bytes:%d\n", sfileLength);
fclose(fs);
}
if (fr_block_sz == 0 || fr_block_sz != 512) {
break;
}
Remove this code. The first part of the test can never be true due to the 'while' condition, and the second part is unnecessary for the same reason.