gerard4143 371 Nearly a Posting Maven

I wrote this simple client/server example that passes an array of structures to the server...This is just a very simple example of passing data between the client and the server...its by no means a rigorous program

If you can find anything of use in it, please feel free to use it.

Usage:
run server ./server&

run client ./client 127.0.0.1

server.c

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <strings.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>

struct mystr
{
	unsigned int one;
	unsigned int two;
	unsigned int three;
	unsigned int four;
};

#define DEFAULT_PROTOCOL 0
#define ARRSIZE 3
#define MAXLINE 7

int main(int argc, char**argv)
{
	int i = 0, n = 0, j = 0;
	struct mystr thestr[ARRSIZE];
	char *ch = (char*)&thestr;

	int listenfd, connfd, val = 1;
	struct sockaddr_in servaddr;

	signal(SIGCHLD, SIG_IGN);

	if ((listenfd = socket(AF_INET, SOCK_STREAM, DEFAULT_PROTOCOL)) < 0)
	{
		perror("socket");
		exit(EXIT_FAILURE);
	}

	setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(50000);
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

	if ((bind(listenfd, (const struct sockaddr*)&servaddr, sizeof(servaddr))) < 0)
	{
		perror("bind");
		exit(EXIT_FAILURE);
	}

	if ((listen(listenfd, 5)) < 0)
	{
		perror("listen");
		exit(EXIT_FAILURE);
	}

	for (;;)
	{
		connfd = accept(listenfd, NULL, NULL);

		if (fork())
		{
			close(connfd);
		}
		else
		{
			j = 0;
			while ((n = read(connfd, &ch[j], MAXLINE)) > 0)
			{
				j += n;		
			}
			for (i = 0; i < 3; ++i)
			{
				fprintf(stdout, "\none->%d, two->%d, three->%d, four->%d\n", thestr[i].one,\
						 thestr[i].two, thestr[i].three, thestr[i].four);
			}
			exit(EXIT_SUCCESS);
		}
	}
	exit(EXIT_SUCCESS);
}

client.c

#include <stdio.h>
#include <stdlib.h> …
gerard4143 371 Nearly a Posting Maven

Well i just figured out that i shouldnt be sending the struct from client to server. What i should do is send the struct field by field, and assemble it on the server so i can pass it to the handletpclient function.

I'm more aqcuaited with programming in java. And in these cases, when you send several messages (that implement the Serializable interface), you can assemble all together at the other side with a "instanceof " test. In C, how can i know which part of the struct just arrived to the server, so we could assemble the struct correctly?

Maybe with a for loop? Each iteration with the arrival of one part? And on the side of the client, another for loop for sending?

You really should pick up a good book on programming with network sockets..

gerard4143 371 Nearly a Posting Maven

You know that htons/ntohs is used on unsigned short not int.

gerard4143 371 Nearly a Posting Maven

The char pointers are passed on the command line too: argv[4] and argv[7]. The structure is filled in with information from the command line at the client and then sent to the server, where i print the information just to see if everything is well.

I think what your doing is passing the pointer values from the client to server. This won't work, you have to pass the values of the character arrays argv[4] and argv[7]..

gerard4143 371 Nearly a Posting Maven

Quick question, how are you passing your char pointers? From what I can see your passing the pointer value and not the characters that make up the character array.
The pointer values from the client application have no valid meaning in your server application.

gerard4143 371 Nearly a Posting Maven

Hi Friends,

I have heard that it isn't that simple to write a program in linux using c.
Lots of commands n stuff.Please simplify what actually I've got to do to run turbo c++ in my linux laptop as I am a beginner.

Its just as easy as any other version of C...If you mean compiling a program in Linux using GCC then that's simple..From the terminal type

gcc filename.c -o filename

and then to run

./filename

I don't think Turbo C++ is ported to Linux so you can't used it in a Linux environment..

gerard4143 371 Nearly a Posting Maven

I want to make a module that print console, current folder name like pwd, but I don't know how with system calls ? or something else ? if system calls, what is the system call of that ? and how can I use this system call on my module.?

I'm pretty sure you can't use system calls in a kernel module.

gerard4143 371 Nearly a Posting Maven

Declaring assembler sections is indeed a fairly nice solution.
However, I tried to limit the number of files to maintain at maximum, and as I already make full use of linker script, I try to make it manage all the memory allocation as it should do (in good sense :-/ )

Thank you for your help. Your solution is elegant, but I keep hoping that the linker script can handle this too, don't you think?
To my mind, it is responsible to final output file creation, isn't it?

Yes the linker ties up everything into a chosen format. Good-luck I hope everything works out..

gerard4143 371 Nearly a Posting Maven

The qualifiers const volatile require the memory section to be "aw" because you can easily step around the const volatile definition - see below

#include <stdio.h>
#include <stdlib.h>

const volatile int testint = 8;

int main(void)
{
	int *intptr = (int*)&testint;
	fprintf(stdout, "ans->%d\n", testint);
	
	*intptr = 88;

	fprintf(stdout, "ans->%d\n", testint);

	exit(EXIT_SUCCESS);
}

So the 'const volatile' is maintained by the compiler and not memory..Plus I compiled with the -S switch and it is define as .data

Why don't you just write that section in assembler like:

.section .G4143, "aw", @progbits
	.global testint
	testint: .quad 78

That way you can create your section any way you want - no second guessing

gerard4143 371 Nearly a Posting Maven

First let me state that I have used linker scripts very infrequently...I'm no expert. You define .flashdata as (wa) which is Read/write and Allocatable and then you place a const volatile variable into that section, is that allowed?

Turns out it is..

gerard4143 371 Nearly a Posting Maven

Hi all,

I face a problem using gcc and ld on embedded target.
I just want to declare a constant value (designed to be located in flash memory), and I want to have it compile, linked and allocated in my output file.

For instance:

const volatile unsigned long myvar __attribute__((section(".flashdata"), used)) = 0xAAAAAAA;

using linker script with:

MEMORY
{
[...]
    flashdata_memory (wa) :         org = 0x20000000,   len = 128K
[..]
};
FORCE_COMMON_ALLOCATION

PHDRS
{
[...]
   flashdata PT_LOAD;
[...]
};

SECTIONS
{
[...]
  .flash_data   :
  {
    . = ALIGN(4);
    *(.flashdata .flashdata.*);
  }  > flashdata_memory :flashdata
[...]
}

the only way to have it allocated is to insert "a" in the section attribute as:

const volatile unsigned long myvar __attribute__((section(".flashdata, [B]\"a\"[/B]"), used)) = 0xAAAAAAA;

I find this dirty as all the variables in my section flashdata should be allocated. :yawn:
Is there a way in the linker script to force the allocation of the section?
(I hope I am not using 'allocation' word for something else..)
I thought FORCE_COMMON_ALLOCATION would help doing so, but it has no effect on my created section.

Thank you for your help,:$

Fred

First let me state that I have used linker scripts very infrequently...I'm no expert. You define .flashdata as (wa) which is Read/write and Allocatable and then you place a const volatile variable into that section, is that allowed?

gerard4143 371 Nearly a Posting Maven

oh, jesus. it's one thing to send the poor guy on a wild goose chase, but another to give him shitty instructions.

So what's wrong with producing this

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>

int main(int argc, char**argv)
{

	char ch;
	const int MULTI = 10;
	int x = 0;

	while (true)
	{
		fputs("enter a number->", stdout);
		while ((ch = fgetc(stdin)) != '\n')
		{
			if (isdigit(ch))
			{
				x = (x * MULTI) + (ch - 48);
			}
			else
			{
				/*do something if it fails*/
				fprintf(stdout, "ch->%c is not a digit\n", ch);
			}
		}
		fprintf(stdout, "ans->%d\n", x);
		x = 0;
	}
	exit(EXIT_SUCCESS);
}
gerard4143 371 Nearly a Posting Maven

thank u
but How i will convert it to integer after this ?

I would get a table of the ascii values and do some arithmetic.

gerard4143 371 Nearly a Posting Maven

but the input is number (integer), how I will check it ?

Try replacing your scanf function with the loop and print each character out:

char ch;

while ((ch = fgetc(stdin)) != '\n')
{
fputc(ch, stdout);
}

Note - When you enter the 'number' in its a string of characters

gerard4143 371 Nearly a Posting Maven

Try checking each character that is entered like below:

char ch;

while ((ch = fgetc(stdin)) != '\n')
{
//check if ch is a digit
}
gerard4143 371 Nearly a Posting Maven

The first example your trying to change a const string - char *ptr = "String";
with the line *str ='T';(Note I assumed str is a typo and should be ptr) which is not allowed

and for the "Hello, World" try:

printf("%s%s","Hello", "World");

gerard4143 371 Nearly a Posting Maven

Jeez have guys heard of "the good samaritan act", I'm sure the person thought he/she was helping. Did it require three senior posters calling this person down...

gerard4143 371 Nearly a Posting Maven

as far as i know, the isdigit function will not work for a large number including commas.
for xample, a number like 43,123,321 wont be handled by the function

The number your referring to is a string of ascii characters...

gerard4143 371 Nearly a Posting Maven

I tried this in Mandriva and it worked

#include <stdio.h>

int main()
{
	char str1[100];
	char str2[100];

	printf("Enter 1st string\n");
	scanf("%[^\n]s",&str1);
	fgetc(stdin);

	printf("Enter 2nd string\n");
	scanf("%[^\n]s",&str2);

	printf("1st string is %s\n", str1);
	printf("2nd string is %s\n", str2);

	return 0;
}
gerard4143 371 Nearly a Posting Maven

I think I understand what you want - try investigating the isdigit() function.

gerard4143 371 Nearly a Posting Maven

Here's an example of passing/allocating a pointer in a function

#include <stdio.h>
#include <stdlib.h>

void Test(char **cptr);

int main()
{
	char *str;

	Test(&str);

	fputs(str, stdout);
	free(str);
	return(0);
}

void Test(char **cptr)
{
	int val = 0;

	printf("How many characters do you want to enter->");
	scanf("%d", &val);
	getc(stdin);

	*cptr = (char*) malloc(val * sizeof(char));

	printf("Enter your text: (DO NOT INCLUDE SPACES)->");
	fgets(*cptr, val, stdin);
}
gerard4143 371 Nearly a Posting Maven

Try the function strcmp or strncmp.

gerard4143 371 Nearly a Posting Maven

hi guys! plz help with the code in C which can calculate the fectorial of 500.

Could we see what you have so far.

gerard4143 371 Nearly a Posting Maven

it destroy the data in my hard dirve.

It really depends by what you mean "it destroy the data in my hard dirve". If you mean the entire USB drive was overwritten then your data is gone. If you mean it changed some of the data on the drive them yes you can probably piece some of it back together through a long and tedious journey of hunting and searching...

In Linux its a simple matter of opening the device in a hexeditor and searching(Note this method assumes you know what the file and disk format is)

Also - shouldn't this be posted in the hardware section

gerard4143 371 Nearly a Posting Maven

Hello,

Im using threads in a recent project. I would like to know whats the difference between:
pthread_kill() and pthread_cancel()

What are the effects of each one?

Thank you!

If your using Linux/Unix try open a terminal and type
man pthread_kill
man pthread_cancel
and it will retrieve all the info you need.

gerard4143 371 Nearly a Posting Maven

Hello,

Can someone explain me what does this mean?

"40[^\"], %*c"

Thanks

Could we see more of the program, so we can see it in context

gerard4143 371 Nearly a Posting Maven

Actually, thinking it over, you probably want something closer to this

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char**argv)
{
	int ch, nc = 0;
	fputs("enter some characters->", stdout);
	
	while ((ch = fgetc(stdin)) != '\n')
	{
		++nc;
	}
	fprintf(stdout, "ans->%d\n", nc);
	exit(EXIT_SUCCESS);
}

Which just counts the number of characters entered

gerard4143 371 Nearly a Posting Maven

Right away I would use the fgets function to get the string from the user and I would define your string as:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char**argv)
{
	char ch[30];
	fputs("enter some characters->", stdout);
	fgets(ch, 29, stdin);
	fprintf(stdout, "string->%s\n", ch);
	exit(EXIT_SUCCESS);
}

This hint should pretty much get you there

gerard4143 371 Nearly a Posting Maven

Boy something is wrong here...This is the C forum

gerard4143 371 Nearly a Posting Maven

hi..pls help me with this ...when i run this c program i get in result segmentation fault message (i run in ubuntu terminal):

#include<stdio.h>
#include<utmp.h>
int main()  {
       char *s,*c;
       struct utmp *u;
       int i;
       c=getlogin();
       setutent();
       u=getutent();
       while(u!=NULL)  {
          if(u->ut_type==7 && strcmp(u->ut_user,c)==0) {
               printf("%-12s",u->ut_user);
               printf("%-9s",u->ut_line);
               s=ctime(&u->ut_time);
               for(i=4;i<16;i++)
               printf("%c",s[i]);
               printf("(%s",u->ut_host);
               printf(") ");
          }
       u=getutent();
       }
}

and when compile i get warnings:
gcc -o who who.c
who.c: In function ‘main’:
who.c:7: warning: assignment makes pointer from integer without a cast
who.c:14: warning: assignment makes pointer from integer without a cast

i must mention that programs must return the same as the command who (linux)
thx...and sry for bad english

I quickly look at your program and this works(I would clean up the hack)

#include<stdio.h>
#include<utmp.h>
#include <unistd.h>
#include <time.h>

int main()  {
       char *s,*c;
       struct utmp *u;
       int i;
       c=getlogin();
       setutent();
       u=getutent();
       while(u!=NULL)  {
          if(u->ut_type==7 && strcmp(u->ut_user,c)==0) {
               printf("%-12s",u->ut_user);
               printf("%-9s",u->ut_line);
               s=ctime((const time_t*)&u->ut_time);	//this was a quick hack
							//you could probably do it better
               for(i=4;i<16;i++)
               printf("%c",s[i]);
               printf("(%s",u->ut_host);
               printf(") ");
          }
       u=getutent();
       }
}

Also main should return 0;
and strcmp should include <string.h>

gerard4143 371 Nearly a Posting Maven

The question is to ask the user to enter a string which might be a number,symbol,letter or mix of these.The string must be of 12 characters long and message should be dispayed to the user as follow:
If he enters less than 3 characters a message is'your string is too short please enter another string'
If he enter more than 12 charcter a message is 'your string is too long please enter another string'
Note: all entered characters must be from ASCII table

For us to reply 'and stay within the forum rules' you must show some effort by posting what you have so far. So please post what you have so far.

gerard4143 371 Nearly a Posting Maven

Please post the code you have so far and the questions...

gerard4143 371 Nearly a Posting Maven

ruenahay pisti kang inatay kang dako dyosa2 pa kuno ungo diay to

kjsdf kshdfk sfdfja weui dsggw dhcjk

gerard4143 371 Nearly a Posting Maven

Hey Guys, Ubuntu just released it's 9.10 version called "karmic Koala". I'm still on the process of updating my old OS but I heard a lot of great things about it. One even mentioned it is a great competitor for Windows 7.

Does anyone have something to share about the Koala?

Tried installing it and...Well lets put it this way, if I wasn't so entrenched in Mandriva I would have switched.

gerard4143 371 Nearly a Posting Maven

>but still compiled and ran without incident..
Yet another ding against gcc for not conforming to the standard

I'm sure GCC will survive...dings and all

gerard4143 371 Nearly a Posting Maven

>I tried compiling this with the GCC compiler and its works...
Try again with the -ansi, -pedantic, and -Wall switches.

I did use -ansi -Wall

When I tried -ansi -Wall -pedantic it generated a warning but still compiled and ran without incident..

gerard4143 371 Nearly a Posting Maven

Hi ,

I read that c is not a block structured language.
means it does not allow defining functions inside other functions.

but this code is not generating any error not even warnings, though we nest the functions.

whats the story.

#include<stdio.h>
int main()      {
        int num;
        num = 10;
        int fun(int n)  {
                printf("The local function");
                return 0;
        }
        fun(num);
        printf("Main function");
        return 0;
        }

I tried compiling this with the GCC compiler and its works...so I tried compiling with the -S switch(Stop after the stage of compilation proper; do not assemble) and found it create a function fun.2047(huh name mangling in C)..Any ways this doesn't answer your questions as to why this is allowed but I'm interested enough to see what someone else comes up with...

gerard4143 371 Nearly a Posting Maven

Try adding this to your if statement:

if(str[i] == 'a')
			{
				a++;
			}
			else if(str[i] == 'b')
			{
				b++;
			}
			else if (str[i] == '\n')
			{
				//this will account for the newline
			}
			else
			{
				stop++;
			}
gerard4143 371 Nearly a Posting Maven

Mmm... Thanks Gerard, if I'm thinking of the right thing (vi enhanced) - mmm... is it possible to I be able to set breakpoints, step over and step into? I think in the least I'll need that.

That would be a debugger your talking about...If you expect your IDE to come fully featured then it won't be lightweight....Can VIM use a debugger? I really don't know because I never tried...

I would look into Code blocks, Gedit, Kwrite, Kdevelop, bluefish...or just Google Linux IDE since most are ported to Windows.

gerard4143 371 Nearly a Posting Maven

If you want simple and complex then try VIM...

gerard4143 371 Nearly a Posting Maven

Hello everyone,
Here's my code for making a dynamic array(the user inputs the size of the array). It's working fine but I think that I've not made the best code. Is there any suggestion for improvement or optimization?

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
	int *p;
	int n,i;
	printf("how many integers do u wanna enter\n");
	scanf("%d",&n);
	p=malloc(n*sizeof(int));
	for(i=0;i<n;i++)
	{
		printf("enter the %d element",i+1);
		scanf("%d",p);
		p++;
	}
	p=p-n;
	for(i=0;i<n;i++)
	{
		printf("%d\n",*(p+i));
	}
	free(p);
}

No the code looks fine..If you want to optimizes try experimenting with the compiler's optimizing settings...

Also you may want to look up VLA or 'variable length arrays'

gerard4143 371 Nearly a Posting Maven

>> I believe no questions are stupid.
That's naive. And I didn't say the questions was stupid. I said the thread was stupid.

How many times does the same thing have to be said before it's registered?

Gerard -- "The include statement is processed by the preprocessor so it can't be dynamically created in the executable..."
Dave Sinkula -- "The #include directive is like a copy-and-paste that happens at compile time. You can't do it at runtime."
AD -- "No because the #inc lude directive is processed at compile time, not runtime."
Me (Ironically) >> The #include thing only works on compile time. Not run time.

Then you finally say -- "The #include thing only works on compile time. Not run time" - so you mean the binary will have all the contents of the the included file???

Its undeniable, the point you make.

gerard4143 371 Nearly a Posting Maven

I am not sure if scanf("%c", part1.pname) is even legal

Then why would you put it in your program?

#
const char *str = &part1; //LINE 28

You have const char *str and your assigning the address of struct parts to it without a cast..

gerard4143 371 Nearly a Posting Maven

So I have this project to program an "auto parts management" C program. Basically I need to be able to add and delete lines of text from a text file. Also, I need to be able to edit lines of text. Lines of text are in the format:

PART NAME : OWNER : STATUS : SYSTEM DATE : CO NAME

Although I don't know much about them, structures would seem like they would be useful. I think in my case it would look like this:

struct parts
{
  char pname [PNAME_LEN+1];
  char owner [OWNER_LEN+1];
  char status [3];                                //toggles between in/out
  char date [10];                                // MM/DD/YYYY format.
  char oname [ONAME_LEN+1];
} part1, part2, part3;                         //etc... I assume I need a loop
                                                //to increment part.

To add a part, the program will prompt the user for a pname and an owner. So once I have those two things captured in variables, I need to initialize part1 so it contains "pname:owner:in" with the date and co name left blank. Will this work?

struct parts part1;
strcpy(part1.pname, pname);
strcpy(part1.oname, owner);
strcpy(part1.status, "in");

How would I then print part1 into a text file?

I would use fwrite

fwrite(&part1, sizeof(struct parts), 1, fd);

Where fd = FILE *stream

gerard4143 371 Nearly a Posting Maven

Note...I tried the above code with a client program I have here and it worked...Meaning it send the data and the client received it...

gerard4143 371 Nearly a Posting Maven

I quickly tried this an it doesn't fail...Note I never worked with AF_INET6...Also i took the liberty of changing some of your constants..

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <strings.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>

char message[] = "This is the server socket message!\n";

int main(){

  int listenSocket;
  int connectSocket;
  int numberOfBytes;
  int yes=1;
  char recvData[4096 + 1];
  char ip6[INET6_ADDRSTRLEN];
  socklen_t sin_size;



  struct sockaddr_in6 serverAddress;
  struct sockaddr_in6 clientAddress;

  if((listenSocket=socket(AF_INET6,SOCK_STREAM,0)) < 0)
  {

    perror("Connect Problem");
	exit(EXIT_FAILURE);	
  }

 /* if(setsockopt(listenSocket,SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(int))==-1){

    perror("Sock Option Problem");
    exit(1);
  }*/

  bzero(&serverAddress,sizeof(serverAddress));

  serverAddress.sin6_family=AF_INET6;
  serverAddress.sin6_addr=in6addr_any;
  serverAddress.sin6_port=htons(50000);

  if ((bind(listenSocket,(struct sockaddr*)&serverAddress,sizeof(serverAddress))) < 0)
  {
  	perror("bind");
	exit(EXIT_FAILURE);
  }

  

  if ((listen(listenSocket,5)) < 0)
  {
  	perror("listen");
	exit(EXIT_FAILURE);
  }

  for(;;){

	
	sin_size=sizeof serverAddress;
	connectSocket= accept(listenSocket, (struct sockaddr *)&clientAddress, &sin_size);

	//if(connectSocket==-1){
		
	//	perror("Problem");
	//}
         
       /* inet_ntop(AF_INET6, &(clientAddress.sin6_addr), ip6, INET6_ADDRSTRLEN);
	printf("The address is: %s\n", ip6);*/


	//send(connectSocket, "Hello World from Server\n", 4096, 0);

	fputs("client connected!\n", stdout);
write(connectSocket, message, strlen(message));

	close(connectSocket);

	}
  printf("I am IPv6 Server\n");
  return 0;
}
gerard4143 371 Nearly a Posting Maven

Try:

connectSocket= accept(listenSocket, NULL, NULL);

Also I would check if an error returned on the two lines

bind(listenSocket,(struct sockaddr*)&serverAddress,sizeof(serverAddress));

listen(listenSocket,BACKLOG);
gerard4143 371 Nearly a Posting Maven

Hi everyone, i have this portion of code

while(c = getc(file) != EOF)

c is an int and file is a FILE *file = fopen(filename, "r");

The filename points to a file with 2 lines, 10 characters total. That while always makes c a value of 1 (accodring to ASCII -> start text, dunno what that mean).
But when i use this while:

while((c = getc(file)) != EOF)

It works perfect. I though that was equivalent...i'm missing something on basic syntax here. What's wrong in the first while?

Thank you.

Try investigating order of operations

gerard4143 371 Nearly a Posting Maven

Not really sure what your question is...well beside the main homework question..

gerard4143 371 Nearly a Posting Maven

Hi all. Just a simple question but I SERIOUSLY need some help from you guys for my programming assignment.

The assignment given was water jug problem.

Now my question is, does C allow for the creation of dynamic array during a recursion?
Suppose I have another function, which returns a value (well in my case the function returns a character), and I'm gonna store the character into a dynamic array(which in the current function). This means that the dynamic array is constantly "enlarged" as long as another function returns a value to the current function where the dynamic array is located. If the other function stops returning a value, the whole process stops.

Thanks in advance.

Dynamic array yes..Look up VLA - variable length arrays