nezachem 616 Practically a Posting Shark

It is important to realize that the child process cannot possibly affect the parent's environment. When you run the command from the executable file, a second copy of bash is forked, it has its environment changed and then dies leaving no trace. The builtins (dot and source for example) are executed in the context of the current process, without forking a child, and the environment modifications stay put.
To make a simple one word command, you may wrap it in the function, and have that function in .bashrc, or some other autosourced file of your preference.

nezachem 616 Practically a Posting Shark

Are you trying to execute the makefile? What about just typing make at the command prompt?

nezachem 616 Practically a Posting Shark

Some numbers are both multiple of 3 AND a multiple of 5. You count such numbers twice.

nezachem 616 Practically a Posting Shark

Is there any benefit to using a child process with fork()?

Definitely so. Doing everything in the same process means that you can either accept or serve. The act of serving (read the request, prepare, and send the reply) is time consuming. That is, server becomes unresponsive.
NB: it is possible to make a good server in a single process, but it is way more complicated.

If I were to do that would I just write the above into a string array and then use the send() function?

Yes.

Plus how will the index.html page be sent?

use the send() function. Don't forget an empty line after the headers.

nezachem 616 Practically a Posting Shark

This is the output on Solaris in the case of vfork():
Segmentation Fault (core dumped)

A vforked child is confined to _exit() and execve(). Anything else causes undefined behaviour.

MS-Windows creates threads just like vfork, where all threads share the same memory.

It does not. After vfork the parent process is blocked until the child does either _exit() or execve. Parent and child never run in parallel while sharing memory space.

But i must confess that i still dont understand , even if fork uses different memory spaces for parent and child, how the ftell(fp) points to a different value after child exits.

The point is that even though parent and child have distinct FILE objects, both of them refer to the same file obect in the kernel. The parent's ftell() obtains the read pointer from this shared object, which is of course affected by child's read().

nezachem 616 Practically a Posting Shark

En is set to 0 at line 11 and never changes after that. Therefore the loop (as long as E is positive) never executes. You need to initialize En to a really big number and reevaluate it at each iteration.

Adak: The code compiles and runs, and the %lf conversion apparently works. What gave you the idea that OP has trouble with floating point?
> Whether that works or not, depends on the relative sizes of integers and doubles, and your compiler design
The int to double promotion is a language feature, and it works always.

nezachem 616 Practically a Posting Shark

Just check errno. It should be set to EINTR.

nezachem 616 Practically a Posting Shark

Before going into windchill, try the experiment, you'd be surprised:

tC = f2c(t);
    tF = c2f(tC);
    cout << "t = " << t << "; tF = " << tF << endl;

The printed out values should be identical. They are not.

Griff0527 commented: excelent testing code. I spotted the error in my c2f code almost immediately by using this +1
nezachem 616 Practically a Posting Shark

> By logic /2 should mean half of sequence

Only if those halves are identical. What would be a result of

(0, 1, 2, 3) / 2
nezachem 616 Practically a Posting Shark

Notice parent 1 . Process with pid 1, aka init, besides other things, adopts every orphan. This means that by the time 6215 prints its message, 6214 is already dead.

nezachem 616 Practically a Posting Shark

> The file is open
No, it just seem to be open. Your openfile function does open a file, but does not pass it back to main. The main's fp remains uninitialized.

nezachem 616 Practically a Posting Shark
class polygon{
  int n;
  point *points;
public:
  polygon(int n){
    point *points=new point[n];
    this->n=n;
  };

At the line 6 you initialize a local variable points . The member points remains uninitialized.

nezachem 616 Practically a Posting Shark

Post your requirements. Until then, no advice is possible.

nezachem 616 Practically a Posting Shark

You have to clear() your stream.
When the line ends with the last number, a corresponding extract hits the end of string, and the stream is in end-of-file condition. Calling str() does not clear it.

nezachem 616 Practically a Posting Shark

Probably, you want to print(value) instead.

PS: note that subprocess.call returns the exit status, not the output. You may want to redirect stdout.

nezachem 616 Practically a Posting Shark

The value is just a pointer

... so it must oblige to the pointer alignment requirements. If the pointer is fetched correctly, the call would succeed. However, if it is stored at the odd boundary, chances are you'd fetch not what you expect.

This UB stems from the architectural issues indeed. On most IA32 based platforms you wouldn't notice anything strange. Still it is an UB and must be avoided.

gerard4143 commented: Thanks for the clear explanation +3
nezachem 616 Practically a Posting Shark
*(unsigned int*)&recvline[0] = 11111;

*(unsigned int*)&recvline[sizeof(unsigned int)] = 22222;
/*this section*/
*(void(**)(void))&recvline[2 * sizeof(unsigned int)] = (void(*)(void))&myhello;
/*this section*/

Casting is not for l-value. Only for r-value.

Correct, but not applicable. The result of cast, e.g. (int *) foo , is not an lvalue, and cannot be assigned. (int *) foo = bar; is incorrect. However, it can be indirected all right. * (int *) foo = baz; is perfectly OK.

Regarding the original post, though well-formed, the code may invoke an undefined behaviour. The alignment of unsigned int (and a function pointer) is stronger than that of a char; a situation specifically mentioned in 6.3.2.3.7 paragraph of a Standard.

jephthah commented: success +7
nezachem 616 Practically a Posting Shark

when you say "have nothing in common with other variables of the same name. " Are you talking about the lettercode and GPA? Am I opening the files incorrectly? Don't you have to use the same variables in the function? the lettercode and GPA never change they just get read from the file? This is horrible I feel so stupid right now.

Removing all irrelevant lines, the OpenFiles function boils down to the following:

void OpenFiles(char& lettercode, double& GPA)
{		
	ifstream input;
	input.open("ch7_ex4.txt");

	ofstream output;
	output.open("GPAout");
}

It declares two local variables input and output , does some magic with them and returns. One very important thing you must realize is that once the function returns, its local variables are gone, as if they never existed. As coded above, the function has the same effect at the rest of the program as if it was

void OpenFiles(char& lettercode, double& GPA)
{		
	ifstream foo;
	foo.open("ch7_ex4.txt");

	ofstream bar;
	bar.open("GPAout");
}

Later on, you try to use input in

void Sum_GPA(char lettercode, double GPA, double& fgpa, double& mgpa, int& fcount, int& mcount)
{	
	ifstream input;
	input >> lettercode;
	input >> GPA;

and again, input is a local variable. It does not relate in any sense to input which was declared in OpenFiles .

nezachem 616 Practically a Posting Shark

I've added the 'ofstream output' to the Print_Detail prototype. The error is that the call Print_Detail doesn't take 5 arguments.

input(lettercode, GPA); line 83 getting the error

No. The error is that input is not a function of 2 arguments. In fact, it is not a function at all. According to the Sum_GPA signature, it is a reference to ifstream . If you want to read something from it, you need to call its methods, e.g.

input >> lettercode;
    input >> GPA;

Before you do that, however, be advised, that the OpenFiles function is meaningless as written. The input and output mentioned there have nothing in common with other variables of the same name.

nezachem 616 Practically a Posting Shark

There's an example at the top of paragraph 20.11 (ftplib) of python documentation. See how a callback is passed to retrbinary. You need a similar setup for your ftp.dir() - or better ftp.retrlines('LIST', callback).

nezachem 616 Practically a Posting Shark

This is a documented behaviour. FTP.dir() returns None. However, it calls a callback function for each line of the transfer. The default callback prints lines to stdout. You need to provide your own callback.

nezachem 616 Practically a Posting Shark

That was it. Good luck. Don't forget to mark the thread solved.

nezachem 616 Practically a Posting Shark

If i'm not mistaken, each child, once completed the transfer closes the file at line 63 and closes connfd at line 64...

... and then exits the if clause, and continues the loop from the beginning. Since it already closed the sockfd, accept() returns immediately with an error, and the loop repeats, eating up all the available processor time.

You are missing a vital call in the child code. It is not related to the networking, but to the process life cycle. Try to figure it out yourself.

nezachem 616 Practically a Posting Shark

Thanks for posting the code. Yet again, as soon as I was able to compile it, run it, and generally play with it, the problem became obvious.

My only gripe now is that for some reason, after the first client is served, the server slows down the computer a whole lot,to the point that it basically freezes it (we're talking two separate computers here).

while(1) {
      connfd=accept(sockfd,(struct sockaddr *)&cliente,&clilen);
      if((pid=fork())==0) {
         ...
      } else {
         close(connfd);
      }
  }

I removed all irrelevant parts. Now tell me, what happens to the child, once it completed the transfer?

On line 51 why are you closing the server socket ? Should that not be like the last step of the program ?

It is the child code. The child doesn't need to listen, and correctly closes its copy of the listener socket right away.

nezachem 616 Practically a Posting Shark

I was planning to write a long response. I was planning to write the same client-server pair myself (and I actually did) to prove that there's nothing wrong with the posted code, and that the problem lies somewhere outside of the fragments you presented.
But at the last moment I noticed a little problem, right there in the server fragment.

if((pid==fork())==0)

Highlighted in red.

Obviously, pid (however (un)initialized it is) does not compare equal to the value returned by fork(); the comparison is false, and both parent and child enter the if clause. That explains all the contradictions, weirdnesses, and inconsistencies in your system behaviour.

The most valuable lesson here is that an incomplete code is impossible to debug.
Even more valuable one is that meditative debugging doesn't worth a dam.

PS:

to use read instead of fgets, and that's my next step, could you please give me the syntax of the function

You already have used them to communicate through the socket. Use write(fileno(fp), buffer, aux) at client.c:12 and read(fileno(fp), archivo, 16) at server.c:13

mitrmkar commented: Nice +5
nezachem 616 Practically a Posting Shark

Please explain lines 19 and 20.

nezachem 616 Practically a Posting Shark

it is a char array

You must realize that until you disclosed this vital piece of information all attempts to help were shots in the dark.

Now you may try to go with a

union u {
    unsigned long SomeLongArray[2];
    char SomeCharArray[8];
};

which will force the alignment, and avoid ugly casts.

nezachem 616 Practically a Posting Shark

I understand what you mean. That professor is known here to be pretty controversial, and i can assure you he said that about fgets. Anyways, without abandoning the fgets and fputs, my mission now is to find a stop condition to the loop in the server, and to prevent the incoming garbage to the buffer. Could this be a way to solve the latter?

while(aux!=0){
  aux=read(sockfd, buffer, 16);

I would prefer

while((aux=read(sockfd, buffer, 16)) > 0)
buffer[aux]='\0'; // In this case, buffer would be buffer[17] instead of buffer[16]

Correct.

if(aux==-1){
  printf("Error en el read");
  }
  else if(strcmp(buffer2,buffer)!=0){
	strcpy(buffer2,buffer);
	fputs(buffer,fp);
   }
    else break;
  }

This is definitely wrong. If the file has 2 identical consecutive strings, you'd terminate transfer prematurely.
You must find the root cause of your original problem. Do not mask it.

nezachem 616 Practically a Posting Shark

I've been able to notice that

fgets(archivo,16,fp)!=NULL

was the one that was giving me the endless loop, my professor said earlier that nowadays it wasn't recommended to use that line

This is a most surprising claim. Either your professor is incompetent, or you misunderstood him. The fact that it gives you a hard time tells that the problem is somewhere else in the program.

the professor is pretty much encouraging us to use fgets, and fputs

In that case you must realize that there is a trouble waiting to happen. Keep in mind, that a read() from the socket may return less data than requested. In your case, the returned chunk may have neither '\n' nor terminating '\0', so fputs will happily send all the trailing garbage to the file.
To use fputs() you must force a '\0' at the proper place in the buffer.

nezachem 616 Practically a Posting Shark

A fairly unorthodox indeed. A standard read/store loop is

while((aux = read(sock, buf, size)) > 0)
    write(out, buf, aux);

Note additional parenthesis in the while condition. Also notice usage of aux in the write call.

Line 13 in the server loop always calculates the same value (either 16 or 4, depending on how archivo is declared), regardless of how many bytes fgets got from the file. The num never becomes 0, with all the consequences. Again, I highly recommend to use read() instead of fgets() .

nezachem 616 Practically a Posting Shark
while(aux=read(sockfd, buffer, 16)!=0)

is not doing what you expect it to do. Hint: it assigns aux a result of comparison.

One side point: you should not use fgets and fputs (at least not as careless as you do). read and write are better suited for the task.

Also, n server.c at line 20:

else close(sockfd);

should be

else close(connfd);
nezachem 616 Practically a Posting Shark

You can't make the return value of that function anything other than an integer. Why? Because they are not normal functions -- it acts more like a self-contained process than another function, except that threads have access to all global data in the entire program. So when a thread returns it just goes back to the operating system much like any other program would do.

Wrong. The thread process is prototyped to return void * with a purpose. You may return anything it wants. The calling thread may collect the returned value via pthread_join() .

In the following code I am calling a function from a pthread:

pthread_create(&threads[t], NULL, dnssearch, (void *)buffer)

I need to pass the string (buffer) to a function and the have the function pass a string back. What am I doing wrong in the function:

Quite a lot. Starting from a possible buffer overflow in fscanf, and invoking undefined behaviour at line 25, to begin with. Dangerously aliasing an argument. Probably not joining the thread.
Also, it is very unclear what the function is supposed to do; its expected result and actual behaviour. Can you explain it in plain English (especially the do loop at lines 15 to 27)?

Ancient Dragon commented: Glad to know that. Not the first time I've been wrong about something :) +28
nezachem 616 Practically a Posting Shark

.data, .bss, etc have nothing to do with the architecture. They represent the structure of an object file. They are linked differently; they are stored differently, they are loaded differently.

nezachem 616 Practically a Posting Shark

I want to know how my local static variable is in .data segment and my global static is in .bss specifically?
One of them ends up in .data, because it is initialized. Another one ends up in .bss because it is not (or, rather, initialized by 0).

and what about that peculiar .1784 naming in that local static variable...
This is how your compiler decided to mangle its name to take it out of the global scope.

nezachem 616 Practically a Posting Shark

Hi, i'm trying to learn some assembly, ive got a assignment from school to control a lcd screen. I've got some sample code that i mostly understand but i can't figure out what the SBI command does.
Using atmega32, with avr studio 4

sbi	PortD, LCD_E

At this point PortD = 32, and LCD_E = 0 (decimal)
After the sbi line PortD = 36

I don't see how he changes from 32 to 36.

.equ	LCD_E	= 2

Do you see now?

Salem commented: Very nice - +20
nezachem 616 Practically a Posting Shark

I wasn't implying full binary search, just a partial binary search.

The problem with even a partial binary search is that if the very first comparison fails (that is, a first marble breaks at the drop from N/2), you need to test the N/2 storeys with a single marble. This gives the worst case of N/2.

PS: You had a slightly different interpretation of the problem. You allow comparison to continue after 2 failures. This is essentially a 3 marble puzzle - which is interesting by itself.
So, having just 1 marble, the problem takes O(N) drops; with 2 marbles it is O(sqrt(N)). What is the asymptotic for 3 marbles? for k marbles?

nezachem 616 Practically a Posting Shark

So here is the algorithm I am trying to design...i'm not sure it will make any sense.
I have a sequence of n numbers(in ascending order). I have an another number 'x'. If i have 2 chances to compare x with a number greater than it but unlimited chances to compare with numbers lesser than it. Now I have to to find out the maximum possible value in the sequence that is less than x in the most efficient way. I know this looks a little contrived but the original question is different so I am looking for the direction I would need to go.

As an example..watch this..

I have a series from 1,2,3,4...............,19, 20.

Now I have a number x = 10.5

Now I have to find the maximum possible number "M" in the series such that M < x

The easiest way would be brute forcing ur way from the lowest possible number(they are in ascending order anyway.). As soon as the "less than comparison" fails, u have the solution. The worst case would 'n' comparisons. But we have two chances where we can fail the comparison. So a slightly better algorithm would be comparing the odd indexed numbers. So in the worst case scenario we have n/2 +1 comparisons which is better than the first.

So far so good. But you still underuse the second chance. Say, you work your way up with an increment of K. The worst case will give you (N/K) + …

nezachem 616 Practically a Posting Shark

just run loops to increment their counter

So far so good.

that would be compared to the integers in the file, so it would be a typical code, like this:

// NOTE: dato is a pointer to a file

  for (x=1; x<=100;x++){
         freq=0;   
           for ( i=0; !feof( dato ) ; i++ ){
				fscanf( dato, "%d", &n );
				if (x==n) freq++;	
           }
       printf ("\n number %d appears %d times", x, freq);
    }

The problem is that I the only frequency result I get is 0. I know it's set to be 0 in the loop, but the value should be printed after each integer is checked and then reset to 0 at the beginning of the next x value, or am I wrong?

One immediate problem here is that after the very first iteration you've reached end of file, and nothing could be read anymore. That said, the approach is horrible.

...
Like I've said I tried the same thing with arrays, to get the loops compare the numbers in file with the ones in one dimensional array and store their frequency in another array, but then freq value is 149086 or something like that.

Most likely you forgot to initialize them. The array is a way to go. BTW, you don't need an array with numbers and comparison loop. A single array with frequencies will do it.

nezachem 616 Practically a Posting Shark

I guess i was just trying to see if someone could pose a rational explanation of why I shouldnt do it with gotos, and give an elegant alternative.

That would be extremely hard. Any rationale against goto stems this way or other from the original Dijkstra article. The point of the article is very valid, yet not applicable to this case. Your approach does not violate the sequentiality of the flow, period.

jephthah commented: well-put. i can live with that :) +7
nezachem 616 Practically a Posting Shark

yeah, i try not to jump between functions, this is just to get out of any single function cleanly in the case of a hardware error.

i guess im just soliciting opinions between doing it the first way (with gotos) or the second (without). or another way i havent considered. i'd rather not use gotos because of the stigma attached to them, but i'm not seeing a cleaner way at the moment.

I don't see anything wrong with gotos here. If you are forced to not use them, then in this particular case you can split the functionality into a worker function and a setup-cleanup wrapper, something along the lines of

int MyDriver_workerFunction(int whatever, char * something)
{
   int errCode = ERROR_CLEAR;   // zero (0) is no error
      if ((errCode = subfunction(val1, val2)) < 0) 
        return errCode;
      // ...
   
      for (port = 0; port < MAX_NUM_PORTS; port++)
      {
         if ((errCode = anotherfunction(port, &status)) < 0) 
            return errCode;

         switch(whatever)
            // ...
      }
      if ((errCode = somethingElse(command, response, something)) < 0) 
         return errCode;
   //...
    return errCode;
}
 int MyDriver_driverFunction(int whatever, char * something)
{
   errCode = MyDriver_workerFunction(whatever, something);
   if (errCode < 0)
      // hardware error-specific exit routines ...
   else 
      // standard exit routines ...

   return errCode;
}
nezachem 616 Practically a Posting Shark

The following is a piece of my dateIOManip.h:

struct fullManip {};
ostream &operator << (ostream &out, fullPtr) {
    Date::Flags[&out] = "full";
    return out;
}

-Josh

Never ever put any definition with global linkage in the include file. An include file may contain only declarations.

nezachem 616 Practically a Posting Shark

I'm trying to write my own system calls. I have a .c file where I'm putting the system calls. My system calls use a struct, so I have declared a global variable that is an array of my struct. Lets just call it

//Stuff is the name of the struct I declared.
Stuff myStuff[100];

I have a function inside of my .c file called "init_Stuff". In order for the stuct to behave properly when a system call it made, init_Stuff must be called one time before any of the system calls will work. From within one of my system calls, I could just say "if the structs aren't initialized yet, go initialize them". But I'm wondering if there is a more elegant/normal way to just call init_Stuff right away. I also have a Makefile that currently just creates an object file of my .c file.

Declare (and define) it with the __init qualifier:

#include <linux/init.h>
void __init init_Stuff();

and call it from linux/init/main.c:start_kernel()

BestJewSinceJC commented: Thanks again +5
nezachem 616 Practically a Posting Shark

Going through the heavyweight processes of assembling the code into an executable and then starting a huge virtual machine emulator is something I want to avoid.

Why?

The thing is that I really just want to analyze the logic of an assembly program automatically using a separate C/C++ program.

A separate C/C++ program, capable of analyzing the logic of an assembly program, especially in an automatic manner, is no lighter than an eimulator.

nezachem 616 Practically a Posting Shark

I seriously doubt that what you are looking for exists. Your goal is achieved by a combination of an assembler, a simulator, and a debugger (the latter two are usually bundled together).
You don't need to modify the simulator code. The process is to assemble your program, load it into a simulator, and run under debugger control. The debugger lets you execute a program line by line, view memory and registers, and even modify them. That's as I understand is what you want.

nezachem 616 Practically a Posting Shark

My apologies for snipping out too much of my code and not providing details.

Accepted.

For us to be on a same page, can you provide a minimal compilable snippet which exhibits the behaviour you observe?

2) So ... should I do a realloc on my_args (and my_env ) to add a NULL pointer after the last string?

Absolutely yes.

3) from the man page: execve() executes the program pointed to by filename. filename must be either a binary executable, or a script starting with a line of the form "#! interpreter [arg]". In the latter case, the interpreter must be a valid pathname for an executable which is not itself a script, which will be invoked as interpreter [arg] filename.

<An attempt to explain deleted. My wording rather confuses than clarifies matters. I'll return to it later>

5) Constant declarations lead to portability problems. I cannot afford portability problems. Besides, I may not know the values of these environment varibles (or how many I might need to supply) prior to run time.

Frankly, I don't see any portability problems here. The second point is very valid, so please disregard my advice.

nezachem 616 Practically a Posting Shark

Few things are obvious right away:
1. cmdstr is not initialized.
2. my_env and my_args are not terminated by NULL.
3. A first element of my_args is a program name. The way you set the arguments up is not fatal, but highly unconventional.
4. You must test the value returned by realloc.
5. You are working too hard. I'd just go with

char * my_env[] = {
    env_ROOT,
    env_EXTRALIBS,
    ....
    env_PATH,
    0
};

and a similar setup for my_args.

nezachem 616 Practically a Posting Shark

if fclose(thefile) is closing all references to the file opened

fclose doesn't close references. It closes a FILE object.
It doesn't matter how many pointers point a particular one. It was opened once, and it must be closed also once.

nezachem 616 Practically a Posting Shark

I recently unrolled an insertion sort and on 60 items it was twice as slow as the looped version. I'm guessing that's because it was too big for the instruction cache, being 1032 KB.

The correct question would be "it was too big for the instruction cache line". I don't know how large is the cache line on your system, but usually it is no more than 512 bytes. It is quite reasonable to expect that an unrolled code doesn't fit a cache line, and suffers all the consequences of extra cache misses, as Salem already explained.

nezachem 616 Practically a Posting Shark

Thou shalt not while(!myfile.eof()) .

Since Dave Sinkula is silent, let me take on this:

while(!myfile.eof())
        {
                        myfile >> circle1 >> op >> circle2;
                        do_something();
        }

Consider the last good iteration. It consumed all the bytes from myfile, but didn't try to read beyond its limits. The end of file hasn't been seen; eof condition has not been set. The loop enters the next round. Of course, the very first read now hits end of file, and whatever you attempt to read is garbage.

nezachem 616 Practically a Posting Shark

Line 55. How current is initialized?